All files / util/src/strings asString.ts

100% Statements 22/22
100% Branches 12/12
100% Functions 1/1
100% Lines 17/17

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 231x     1x 20028x 20028x 20026x 20026x 20026x 20026x 20026x 23320x 23320x 3318x 2x 2x 2x     24x 12x    
const stringify = JSON.stringify;
 
/** Serialize text as a JSON string value. */
export const asString = (str: string) => {
  const length = str.length;
  if (length > 41) return stringify(str);
  let result = '';
  let last = 0;
  let found = false;
  let point = 255;
  for (let i = 0; i < length && point >= 32; i++) {
    point = str.charCodeAt(i);
    if (point >= 0xd800 && point <= 0xdfff) return stringify(str);
    if (point === 34 || point === 92) {
      result += str.slice(last, i) + '\\';
      last = i;
      found = true;
    }
  }
  if (point < 32) return stringify(str);
  return '"' + (!found ? str : result + str.slice(last)) + '"';
};