UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

39 lines (38 loc) 1.54 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toTree = void 0; const printTree_1 = require("tree-dump/lib/printTree"); const stringify_1 = require("./stringify"); const isPrimitive = (value) => typeof value !== 'object' || value === null; const isOneLineValue = (value) => { if (isPrimitive(value)) return true; if (value instanceof Array && !value.length) return true; if (value && typeof value === 'object' && !Object.keys(value).length) return true; return false; }; const isSimpleString = (str) => /^[a-z0-9]+$/i.test(str); const toTree = (value, tab = '') => { if (value instanceof Array) { if (value.length === 0) return '[]'; return (0, printTree_1.printTree)(tab, value.map((v, i) => (tab) => { return `[${i}]${isOneLineValue(v) ? ': ' : ''}${(0, exports.toTree)(v, tab + ' ')}`; })).slice(tab ? 0 : 1); } else if (value && typeof value === 'object') { const keys = Object.keys(value); if (keys.length === 0) return '{}'; return (0, printTree_1.printTree)(tab, keys.map((k) => (tab) => { const addQuotes = !isSimpleString(k); const formattedKey = addQuotes ? JSON.stringify(k) : k; const val = value[k]; return `${formattedKey}${isOneLineValue(val) ? ' = ' : ''}${(0, exports.toTree)(val, tab)}`; })).slice(tab ? 0 : 1); } return (0, stringify_1.stringify)(value); }; exports.toTree = toTree;