UNPKG

@dipscope/type-manager

Version:

Transform JSON strings or plain objects into JS class instances.

62 lines 2.31 kB
export function jsonStringify(x, replacer, space) { const spacing = typeof space === 'number' ? new Array(isFinite(space) ? space + 1 : 0).join(' ') : (space !== null && space !== void 0 ? space : ''); const separator = spacing ? ': ' : ':'; const seen = new Set(); const indents = ['']; const indentify = (level) => { while (indents.length <= level) { indents.push(indents[indents.length - 1] + spacing); } return indents[level]; }; const stringify = (parent, key, node, level) => { if (node && node.toJSON && typeof node.toJSON === 'function') { node = node.toJSON(); } if (replacer) { node = replacer.call(parent, key, node); } if (node === undefined) { return ''; } if (node === null) { return 'null'; } if (typeof node === 'number') { return isFinite(node) ? String(node) : 'null'; } if (typeof node !== 'object') { return JSON.stringify(node); } if (seen.has(node)) { return 'null'; } seen.add(node); const indent = spacing ? '\n' + indentify(level + 1) : ''; const closingIndent = spacing ? '\n' + indentify(level) : ''; const parts = new Array(); if (Array.isArray(node)) { for (let i = 0; i < node.length; i++) { const value = stringify(node, String(i), node[i], level + 1) || 'null'; parts.push(`${indent}${value}`); } const result = `[${parts.join(',')}${closingIndent}]`; seen.delete(node); return result; } const nodeKeys = Object.keys(node).sort(); for (let i = 0; i < nodeKeys.length; i++) { const nodeKey = nodeKeys[i]; const value = stringify(node, nodeKey, node[nodeKey], level + 1); if (value === '') { continue; } parts.push(`${indent}${JSON.stringify(nodeKey)}${separator}${value}`); } const result = `{${parts.join(',')}${closingIndent}}`; seen.delete(node); return result; }; return stringify({ '': x }, '', x, 0); } //# sourceMappingURL=json-stringify.js.map