All files / json-patch-ot/transforms xStrDel.ts

85.29% Statements 29/34
80% Branches 16/20
100% Functions 1/1
86.2% Lines 25/29

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 37 381x   1x 11x 3x 3x 1x 1x   2x     8x 8x 8x 8x 8x 8x 4x 4x 2x 2x   4x 2x 2x 2x   2x 1x     1x          
import {type Op, OpStrDel, OpStrIns} from '../../json-patch/op';
 
export const xStrDel = (del: OpStrDel, op: Op): null | Op | Op[] => {
  if (op instanceof OpStrIns) {
    const ins = op;
    if (ins.pos > del.pos) {
      const deleteLength = del.deleteLength();
      return new OpStrIns(ins.path, op.pos - deleteLength, op.str);
    }
    return op;
  }
 
  if (op instanceof OpStrDel) {
    const opLen = op.deleteLength();
    const delLen = del.deleteLength();
    const overlapLen1 = del.pos + delLen - op.pos;
    const overlapLen2 = op.pos + opLen - del.pos;
    if (del.pos <= op.pos && overlapLen1 > 0) {
      const newLen = opLen - overlapLen1;
      if (newLen <= 0) return null;
      if (typeof op.str === 'string')
        return new OpStrDel(op.path, op.pos - (delLen - overlapLen1), op.str.substr(overlapLen1), undefined);
      else Ereturn new OpStrDel(op.path, op.pos, undefined, newLen);
    } else if (del.pos >= op.pos && overlapLen2 > 0) {
      const newLen = del.pos - op.pos + Math.max(0, overlapLen2 - delLen);
      Iif (newLen <= 0) return null;
      if (typeof op.str === 'string') return new OpStrDel(op.path, op.pos, op.str.substr(0, newLen), undefined);
      else Ereturn new OpStrDel(op.path, op.pos, undefined, newLen);
    } else if (del.pos < op.pos) {
      if (typeof op.str === 'string') return new OpStrDel(op.path, op.pos - delLen, op.str, undefined);
      else Ereturn new OpStrDel(op.path, op.pos - delLen, undefined, op.len);
    }
    return op;
  }
 
  return op;
};