All files / json-patch/op OpMove.ts

95% Statements 19/20
100% Branches 2/2
85.71% Functions 6/7
95% Lines 19/20

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 48 49 50 51 52 53 54 55  16x   16x 16x 16x 16x           16x     120x   120x       17x               93x 93x 92x       17x               8x 8x       4x 4x 4x 4x      
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';
import type {IMessagePackEncoder} from '@jsonjoy.com/json-pack/lib/msgpack';
 
/**
 * @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];
  }
 
  public encode(encoder: IMessagePackEncoder, parent?: AbstractOp) {
    encoder.encodeArrayHeader(3);
    encoder.writer.u8(OPCODE.move);
    encoder.encodeArray(this.path as unknown[]);
    encoder.encodeArray(this.from as unknown[]);
  }
}