All files / json-text toTree.ts

100% Statements 33/33
96.42% Branches 27/28
100% Functions 8/8
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 371x 1x   17x 1x 17x 7x 6x 4x   6x   1x 31x 6x 4x   11x 11x     25x 8x 8x 6x   6x 6x 6x 6x 6x       17x    
import {printTree} from 'tree-dump/lib/printTree';
import {stringify} from './stringify';
 
const isPrimitive = (value: unknown): boolean => typeof value !== 'object' || value === null;
const isOneLineValue = (value: unknown): boolean => {
  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: string) => /^[a-z0-9]+$/i.test(str);
 
export const toTree = (value: unknown, tab: string = ''): string => {
  if (value instanceof Array) {
    if (value.length === 0) return '[]';
    return printTree(
      tab,
      value.map((v, i) => (tab: string) => {
        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: string) => {
        const addQuotes = !isSimpleString(k);
        const formattedKey = addQuotes ? JSON.stringify(k) : k;
        const val = (value as any)[k];
        return `${formattedKey}${isOneLineValue(val) ? ' = ' : ''}${toTree(val, tab)}`;
      }),
    ).slice(tab ? 0 : 1);
  }
  return stringify(value);
};