Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle Map/Set objects in template interpolation (Fix#1067) #1100

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions packages/shared/__tests__/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { toDisplayString } from '../src'

test('toDisplayString', () => {
expect(toDisplayString(null)).toBe(``)
expect(toDisplayString([1, 2, 3])).toBe(`[
1,
2,
3
]`)
expect(
toDisplayString({
foo: 'bar',
baz: 1
})
).toBe(`{
"foo": "bar",
"baz": 1
}`)
expect(toDisplayString(new Map<any, any>([['foo', 'bar'], ['baz', 1]])))
.toBe(`{
"dataType": "Map",
"value": [
[
"foo",
"bar"
],
[
"baz",
1
]
]
}`)
expect(toDisplayString(new Set<any>([1, 2, 3]))).toBe(`{
"dataType": "Set",
"value": [
1,
2,
3
]
}`)
})
32 changes: 27 additions & 5 deletions packages/shared/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,33 @@ export const hasChanged = (value: any, oldValue: any): boolean =>

// For converting {{ interpolation }} values to displayed strings.
export const toDisplayString = (val: unknown): string => {
return val == null
? ''
: isArray(val) || (isPlainObject(val) && val.toString === objectToString)
? JSON.stringify(val, null, 2)
: String(val)
if (val == null) return ''
if (isArray(val) || (isPlainObject(val) && val.toString === objectToString)) {
return JSON.stringify(val, null, 2)
}
if (val instanceof Map || val instanceof Set) {
return JSON.stringify(
val,
function replacer(key, value) {
const originalObject = this[key]
if (originalObject instanceof Map) {
return {
dataType: 'Map',
value: Array.from(originalObject.entries())
}
}
if (originalObject instanceof Set) {
return {
dataType: 'Set',
value: Array.from(originalObject.values())
}
}
return value
},
2
)
}
return String(val)
}

export const invokeArrayFns = (fns: Function[], arg?: any) => {
Expand Down