All files / json-patch/codegen/ops add.ts

100% Statements 10/10
100% Branches 0/0
100% Functions 2/2
100% Lines 7/7

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  4x   4x   4x 50x 50x                                   50x           50x  
import type {OpAdd} from '../../op';
import {type JavaScriptLinked, compileClosure, type JavaScript} from '@jsonjoy.com/util/lib/codegen';
import type {ApplyFn} from '../types';
import {$findRef} from '@jsonjoy.com/json-pointer/lib/codegen/findRef';
 
export const $$add = (op: OpAdd): JavaScriptLinked<ApplyFn> => {
  const find = $findRef(op.path);
  const js = /* js */ `
(function(find, path){
  return function(doc){
    var value = ${JSON.stringify(op.value)};
    var f = find(doc);
    var obj = f.obj, key = f.key, val = f.val;
    if (!obj) doc = value;
    else if (typeof key === 'string') obj[key] = value;
    else {
      var length = obj.length;
      if (key < length) obj.splice(key, 0, value);
      else if (key > length) throw new Error('INVALID_INDEX');
      else obj.push(value);
    }
    return doc;
  };
})`;
 
  return {
    deps: [find, op.path] as unknown[],
    js: js as JavaScript<(...deps: unknown[]) => ApplyFn>,
  };
};
 
export const $add = (op: OpAdd): ApplyFn => compileClosure($$add(op));