function stringify()

in packages/json-stringify-ordered/src/index.ts [31:76]


  function stringify(parent: unknown, key: string | number, node: any, level: number): string | undefined { // eslint-disable-line @typescript-eslint/no-explicit-any
    const indent = space ? `\n${new Array(level + 1).join(space)}` : '';
    const colonSeparator = space ? ': ' : ':';
    
    if (node && node.toJSON && typeof node.toJSON === 'function') {
      node = node.toJSON();
    }
    
    if (replacer) {
      node = replacer.call(parent, key, node);
    }
    
    if (node === undefined) {
      return;
    }
    
    if (typeof node !== 'object' || node === null) {
      return JSON.stringify(node);
    }
    
    if (Array.isArray(node)) {
      return `[${node.map((v, i) => `${indent}${space}${stringify(node, i, v, level + 1) || 'null'}`).join(',')}${indent}]`;
    }
    
    if (seen.indexOf(node) !== -1) {
      if (cycles) {
        return JSON.stringify('__cycle__');
      }
      
      throw new TypeError('Converting circular structure to JSON');
    } else {
      seen.push(node);
    }
    
    seen.splice(seen.indexOf(node), 1);
    
    return `{${Object.keys(node).sort(compareFn ? compareFn(node) : undefined).reduce((result: string[], v): string[] => {
      const value = stringify(node, v, node[v], level + 1);
      
      if (value) {
        result.push(`${indent}${space}${JSON.stringify(v)}${colonSeparator}${value}`);
      }
      
      return result;
    }, []).join(',')}${indent}}`;
  }