All files / json-stable index.ts

100% Statements 30/30
100% Branches 9/9
100% Functions 1/1
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     1x   1x   3849x   1105x   2327x 918x 918x 918x 918x 918x   1409x 1351x 1351x 1351x 1351x 1351x 2990x 2990x 2990x 2990x 2990x   1351x   417x      
import {escape as esc} from '@jsonjoy.com/util/lib/strings/escape';
import {sort} from '@jsonjoy.com/util/lib/sort/insertion';
import type {json_string} from '@jsonjoy.com/util/lib/json-brand';
 
const getKeys = Object.keys;
 
export const stringify = <T>(val: T): json_string<T> => {
  let i: number, max: number, str: string, keys: string[], key: string, propVal: unknown;
  switch (typeof val) {
    case 'string':
      return ('"' + esc(val) + '"') as json_string<T>;
    case 'object':
      if (val instanceof Array) {
        str = '[';
        max = val.length - 1;
        for (i = 0; i < max; i++) str += stringify(val[i]) + ',';
        if (max >= 0) str += stringify(val[i]);
        return (str + ']') as json_string<T>;
      }
      if (val === null) return 'null' as json_string<T>;
      keys = sort(getKeys(val));
      max = keys.length;
      str = '{';
      i = 0;
      while (i < max) {
        key = keys[i];
        propVal = stringify((val as Record<string, unknown>)[key]);
        if (i && str !== '') str += ',';
        str += '"' + esc(key) + '":' + propVal;
        i++;
      }
      return (str + '}') as json_string<T>;
    default:
      return String(val) as json_string<T>;
  }
};