All files / json-patch-ot transform.ts

100% Statements 18/18
100% Branches 4/4
100% Functions 1/1
100% Lines 14/14

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  1x                       1x 91x 91x 91x 91x 91x 91x 91x 97x 97x 96x   91x     91x    
import type {Op} from '../json-patch/op';
import {xforms} from './transforms';
 
/**
 * Takes array of proposed patches and transforms them against an array of
 * already accepted patches.
 *
 * @param accepted Array of already accepted operations.
 * @param proposed Array of proposed operations. Proposed operations are mutated inline.
 * @param acceptedWins Whether accepted operation should win on when paths match exactly.
 *
 * @returns Array of transformed changes
 */
export const transform = (accepted: readonly Op[], proposed: readonly Op[]): readonly Op[] => {
  const length = accepted.length;
  for (let i = 0; i < length; i++) {
    const against = accepted[i];
    const transformFunction = (xforms as any)[against.op()];
    if (transformFunction) {
      const transformed: Op[] = [];
      for (const op of proposed) {
        const newOps = transformFunction(against, op);
        if (Array.isArray(newOps)) transformed.push(...newOps);
        else if (newOps) transformed.push(newOps);
      }
      proposed = transformed;
    }
  }
  return proposed;
};