UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

35 lines (34 loc) 1.34 kB
import { printTree } from 'tree-dump/lib/printTree'; import { stringify } from './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); export const toTree = (value, tab = '') => { if (value instanceof Array) { if (value.length === 0) return '[]'; return printTree(tab, value.map((v, i) => (tab) => { return `[${i}]${isOneLineValue(v) ? ': ' : ''}${toTree(v, tab + ' ')}`; })).slice(tab ? 0 : 1); } else if (value && typeof value === 'object') { const keys = Object.keys(value); if (keys.length === 0) return '{}'; return 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) ? ' = ' : ''}${toTree(val, tab)}`; })).slice(tab ? 0 : 1); } return stringify(value); };