feat(shared): support Map and Set in toDisplayString
close #1067, close #1100
This commit is contained in:
@@ -11,6 +11,7 @@ export * from './domTagConfig'
|
||||
export * from './domAttrConfig'
|
||||
export * from './escapeHtml'
|
||||
export * from './looseEqual'
|
||||
export * from './toDisplayString'
|
||||
|
||||
export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__
|
||||
? Object.freeze({})
|
||||
@@ -112,15 +113,6 @@ export const capitalize = cacheStringFunction(
|
||||
export const hasChanged = (value: any, oldValue: any): boolean =>
|
||||
value !== oldValue && (value === value || oldValue === oldValue)
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
export const invokeArrayFns = (fns: Function[], arg?: any) => {
|
||||
for (let i = 0; i < fns.length; i++) {
|
||||
fns[i](arg)
|
||||
|
||||
28
packages/shared/src/toDisplayString.ts
Normal file
28
packages/shared/src/toDisplayString.ts
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user