Skip to content

Commit

Permalink
fix(shared): handle Map with symbol keys in toDisplayString (#9731)
Browse files Browse the repository at this point in the history
close #9727
  • Loading branch information
pikax committed Dec 7, 2023
1 parent 5b00286 commit 364821d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
22 changes: 22 additions & 0 deletions packages/shared/__tests__/toDisplayString.spec.ts
Expand Up @@ -171,4 +171,26 @@ describe('toDisplayString', () => {
}"
`)
})

//#9727
test('Map with Symbol keys', () => {
const m = new Map<any, any>([
[Symbol(), 'foo'],
[Symbol(), 'bar'],
[Symbol('baz'), 'baz']
])
expect(toDisplayString(m)).toMatchInlineSnapshot(`
"{
\\"Map(3)\\": {
\\"Symbol(0) =>\\": \\"foo\\",
\\"Symbol(1) =>\\": \\"bar\\",
\\"Symbol(baz) =>\\": \\"baz\\"
}
}"
`)
// confirming the symbol renders Symbol(foo)
expect(toDisplayString(new Map([[Symbol('foo'), 'foo']]))).toContain(
String(Symbol('foo'))
)
})
})
16 changes: 11 additions & 5 deletions packages/shared/src/toDisplayString.ts
Expand Up @@ -6,7 +6,8 @@ import {
isPlainObject,
isSet,
objectToString,
isString
isString,
isSymbol
} from './general'

/**
Expand All @@ -31,10 +32,15 @@ const replacer = (_key: string, val: any): any => {
return replacer(_key, val.value)
} else if (isMap(val)) {
return {
[`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
;(entries as any)[`${key} =>`] = val
return entries
}, {})
[`Map(${val.size})`]: [...val.entries()].reduce(
(entries, [key, val], i) => {
entries[
`${isSymbol(key) ? `Symbol(${key.description ?? i})` : key} =>`
] = val
return entries
},
{} as Record<string, any>
)
}
} else if (isSet(val)) {
return {
Expand Down

0 comments on commit 364821d

Please sign in to comment.