Skip to content

Commit 983d45d

Browse files
committedDec 7, 2023
fix(shared): handle more Symbol cases in toDisplayString
1 parent 364821d commit 983d45d

File tree

2 files changed

+35
-8
lines changed

2 files changed

+35
-8
lines changed
 

‎packages/shared/__tests__/toDisplayString.spec.ts

+27-4
Original file line numberDiff line numberDiff line change
@@ -181,10 +181,10 @@ describe('toDisplayString', () => {
181181
])
182182
expect(toDisplayString(m)).toMatchInlineSnapshot(`
183183
"{
184-
\\"Map(3)\\": {
185-
\\"Symbol(0) =>\\": \\"foo\\",
186-
\\"Symbol(1) =>\\": \\"bar\\",
187-
\\"Symbol(baz) =>\\": \\"baz\\"
184+
"Map(3)": {
185+
"Symbol(0) =>": "foo",
186+
"Symbol(1) =>": "bar",
187+
"Symbol(baz) =>": "baz"
188188
}
189189
}"
190190
`)
@@ -193,4 +193,27 @@ describe('toDisplayString', () => {
193193
String(Symbol('foo'))
194194
)
195195
})
196+
197+
test('Set with Symbol values', () => {
198+
const s = new Set([Symbol('foo'), Symbol('bar'), Symbol()])
199+
expect(toDisplayString(s)).toMatchInlineSnapshot(`
200+
"{
201+
"Set(3)": [
202+
"Symbol(foo)",
203+
"Symbol(bar)",
204+
"Symbol()"
205+
]
206+
}"
207+
`)
208+
})
209+
210+
test('Object with Symbol values', () => {
211+
expect(toDisplayString({ foo: Symbol('x'), bar: Symbol() }))
212+
.toMatchInlineSnapshot(`
213+
"{
214+
"foo": "Symbol(x)",
215+
"bar": "Symbol()"
216+
}"
217+
`)
218+
})
196219
})

‎packages/shared/src/toDisplayString.ts

+8-4
Original file line numberDiff line numberDiff line change
@@ -34,20 +34,24 @@ const replacer = (_key: string, val: any): any => {
3434
return {
3535
[`Map(${val.size})`]: [...val.entries()].reduce(
3636
(entries, [key, val], i) => {
37-
entries[
38-
`${isSymbol(key) ? `Symbol(${key.description ?? i})` : key} =>`
39-
] = val
37+
entries[stringiySymbol(key, i) + ' =>'] = val
4038
return entries
4139
},
4240
{} as Record<string, any>
4341
)
4442
}
4543
} else if (isSet(val)) {
4644
return {
47-
[`Set(${val.size})`]: [...val.values()]
45+
[`Set(${val.size})`]: [...val.values()].map(v => stringiySymbol(v))
4846
}
47+
} else if (isSymbol(val)) {
48+
return stringiySymbol(val)
4949
} else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
50+
// native elements
5051
return String(val)
5152
}
5253
return val
5354
}
55+
56+
const stringiySymbol = (v: unknown, i: number | string = ''): any =>
57+
isSymbol(v) ? `Symbol(${v.description ?? i})` : v

0 commit comments

Comments
 (0)
Please sign in to comment.