Skip to content

Commit 364821d

Browse files
authored
fix(shared): handle Map with symbol keys in toDisplayString (#9731)
close #9727
1 parent 5b00286 commit 364821d

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

packages/shared/__tests__/toDisplayString.spec.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,4 +171,26 @@ describe('toDisplayString', () => {
171171
}"
172172
`)
173173
})
174+
175+
//#9727
176+
test('Map with Symbol keys', () => {
177+
const m = new Map<any, any>([
178+
[Symbol(), 'foo'],
179+
[Symbol(), 'bar'],
180+
[Symbol('baz'), 'baz']
181+
])
182+
expect(toDisplayString(m)).toMatchInlineSnapshot(`
183+
"{
184+
\\"Map(3)\\": {
185+
\\"Symbol(0) =>\\": \\"foo\\",
186+
\\"Symbol(1) =>\\": \\"bar\\",
187+
\\"Symbol(baz) =>\\": \\"baz\\"
188+
}
189+
}"
190+
`)
191+
// confirming the symbol renders Symbol(foo)
192+
expect(toDisplayString(new Map([[Symbol('foo'), 'foo']]))).toContain(
193+
String(Symbol('foo'))
194+
)
195+
})
174196
})

packages/shared/src/toDisplayString.ts

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ import {
66
isPlainObject,
77
isSet,
88
objectToString,
9-
isString
9+
isString,
10+
isSymbol
1011
} from './general'
1112

1213
/**
@@ -31,10 +32,15 @@ const replacer = (_key: string, val: any): any => {
3132
return replacer(_key, val.value)
3233
} else if (isMap(val)) {
3334
return {
34-
[`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
35-
;(entries as any)[`${key} =>`] = val
36-
return entries
37-
}, {})
35+
[`Map(${val.size})`]: [...val.entries()].reduce(
36+
(entries, [key, val], i) => {
37+
entries[
38+
`${isSymbol(key) ? `Symbol(${key.description ?? i})` : key} =>`
39+
] = val
40+
return entries
41+
},
42+
{} as Record<string, any>
43+
)
3844
}
3945
} else if (isSet(val)) {
4046
return {

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy