Repository URL to install this package:
|
Version:
1.1.10 ▾
|
/**
* @todo swap with uxui-modules @@perf
*/
// https://github.com/isaacs/json-stringify-safe
// const MAX_SPLICE_SIZE = require('chain/src/deps/native/MAX_SPLICE_SIZE')
// const isNil = require('chain/src/deps/is/nullOrUndefined')
// const MAX_SPLICE_SIZE = require('../src/deps/native/MAX_SPLICE_SIZE')
// const isNil = require('../src/deps/is/nullOrUndefined')
// const isNil = (x: any): boolean => x === undefined && x === null
const isNil = (x: any): boolean => !x
const MAX_SPLICE_SIZE = 10000
// const reference = JSON.stringify
// JSON.stringify = toObjNotationString
// JSON.restore = reference
export type SerializableType =
| SerializableObj
| SerializableArray
| string
| number
| undefined
| null
export interface SerializableObj {
[key: string]: SerializableType
[key: number]: SerializableType
}
export type SerializableArray = Array<
SerializableObj | string | number | undefined | null
>
export type Serializable = SerializableObj | SerializableArray
function toObjNotationString(
obj: Serializable,
replacer?: any,
spaces?: string,
cycleReplacer?: any
) {
return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces)
}
function serializer(replacer: any, cycleReplacer: any) {
const stack = []
const keys = []
if (isNil(cycleReplacer)) {
// tslint:disable-next-line
cycleReplacer = function(key: string | number, value: SerializableType) {
return stack[0] === value
? '[Circular ~]'
: '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'
}
}
return function(key: string | number, value: SerializableType) {
if (stack.length > 0) {
let thisPos = stack.indexOf(this)
~thisPos ? stack.splice(thisPos + 1) : stack.push(this)
~thisPos ? keys.splice(thisPos, MAX_SPLICE_SIZE, key) : keys.push(key)
if (~stack.indexOf(value)) {
value = cycleReplacer.call(this, key, value)
}
} else {
stack.push(value)
}
return isNil(replacer) ? value : replacer.call(this, key, value)
}
}
export { toObjNotationString as stringify }
export default toObjNotationString