Skip to content

Commit

Permalink
fix(shared): handle more Symbol cases in toDisplayString
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Dec 7, 2023
1 parent 364821d commit 983d45d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 8 deletions.
31 changes: 27 additions & 4 deletions packages/shared/__tests__/toDisplayString.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,10 @@ describe('toDisplayString', () => {
])
expect(toDisplayString(m)).toMatchInlineSnapshot(`
"{
\\"Map(3)\\": {
\\"Symbol(0) =>\\": \\"foo\\",
\\"Symbol(1) =>\\": \\"bar\\",
\\"Symbol(baz) =>\\": \\"baz\\"
"Map(3)": {
"Symbol(0) =>": "foo",
"Symbol(1) =>": "bar",
"Symbol(baz) =>": "baz"
}
}"
`)
Expand All @@ -193,4 +193,27 @@ describe('toDisplayString', () => {
String(Symbol('foo'))
)
})

test('Set with Symbol values', () => {
const s = new Set([Symbol('foo'), Symbol('bar'), Symbol()])
expect(toDisplayString(s)).toMatchInlineSnapshot(`
"{
"Set(3)": [
"Symbol(foo)",
"Symbol(bar)",
"Symbol()"
]
}"
`)
})

test('Object with Symbol values', () => {
expect(toDisplayString({ foo: Symbol('x'), bar: Symbol() }))
.toMatchInlineSnapshot(`
"{
"foo": "Symbol(x)",
"bar": "Symbol()"
}"
`)
})
})
12 changes: 8 additions & 4 deletions packages/shared/src/toDisplayString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,24 @@ const replacer = (_key: string, val: any): any => {
return {
[`Map(${val.size})`]: [...val.entries()].reduce(
(entries, [key, val], i) => {
entries[
`${isSymbol(key) ? `Symbol(${key.description ?? i})` : key} =>`
] = val
entries[stringiySymbol(key, i) + ' =>'] = val
return entries
},
{} as Record<string, any>
)
}
} else if (isSet(val)) {
return {
[`Set(${val.size})`]: [...val.values()]
[`Set(${val.size})`]: [...val.values()].map(v => stringiySymbol(v))
}
} else if (isSymbol(val)) {
return stringiySymbol(val)
} else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
// native elements
return String(val)
}
return val
}

const stringiySymbol = (v: unknown, i: number | string = ''): any =>
isSymbol(v) ? `Symbol(${v.description ?? i})` : v

0 comments on commit 983d45d

Please sign in to comment.