All files / json-patch/op OpMove.ts

100% Statements 16/16
100% Branches 2/2
100% Functions 6/6
100% Lines 16/16

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 38 39 40 41 42 43 44 45 46 47  18x   18x 18x 18x 18x         18x     120x   120x       17x       4x       93x 93x 92x       17x               8x 8x      
import type {CompactMoveOp, OPCODE_MOVE} from '../codec/compact/types';
import {AbstractOp} from './AbstractOp';
import type {OperationMove} from '../types';
import {OpRemove} from './OpRemove';
import {OpAdd} from './OpAdd';
import {type Path, toPath, formatJsonPointer} from '@jsonjoy.com/json-pointer';
import {OPCODE} from '../constants';
 
/**
 * @category JSON Patch
 */
export class OpMove extends AbstractOp<'move'> {
  constructor(
    path: Path,
    public readonly from: Path,
  ) {
    super(path);
  }
 
  public op() {
    return 'move' as const;
  }
 
  public code() {
    return OPCODE.move;
  }
 
  public apply(doc: unknown) {
    const remove = new OpRemove(toPath(this.from), undefined).apply(doc);
    const add = new OpAdd(this.path, remove.old).apply(remove.doc);
    return add;
  }
 
  public toJson(parent?: AbstractOp): OperationMove {
    return {
      op: 'move',
      path: formatJsonPointer(this.path),
      from: formatJsonPointer(this.from),
    };
  }
 
  public toCompact(parent: undefined | AbstractOp, verbose: boolean): CompactMoveOp {
    const opcode: OPCODE_MOVE = verbose ? 'move' : OPCODE.move;
    return [opcode, this.path, this.from];
  }
}