feat(shared): support Map and Set in toDisplayString

close #1067, close #1100
This commit is contained in:
Evan You
2020-05-04 10:38:03 -04:00
parent ff97be15c3
commit 3c60d40827
3 changed files with 136 additions and 9 deletions

View File

@@ -0,0 +1,28 @@
import { isArray, isObject, isPlainObject } from './index'
// For converting {{ interpolation }} values to displayed strings.
export const toDisplayString = (val: unknown): string => {
return val == null
? ''
: isObject(val)
? JSON.stringify(val, replacer, 2)
: String(val)
}
const replacer = (_key: string, val: any) => {
if (val instanceof Map) {
return {
[`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
;(entries as any)[`${key} =>`] = val
return entries
}, {})
}
} else if (val instanceof Set) {
return {
[`Set(${val.size})`]: [...val.values()]
}
} else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
return String(val)
}
return val
}