All files / json-patch/op OpFlip.ts

94.44% Statements 17/18
100% Branches 4/4
83.33% Functions 5/6
94.11% Lines 16/17

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  15x   15x 15x           15x   12x               60x 60x 20x 60x       10x       10x       8x 8x       4x 4x 4x      
import type {CompactFlipOp, OPCODE_FLIP} from '../codec/compact/types';
import {AbstractOp} from './AbstractOp';
import type {OperationFlip} from '../types';
import {find, type Path, formatJsonPointer} from '@jsonjoy.com/json-pointer';
import {OPCODE} from '../constants';
import type {IMessagePackEncoder} from '@jsonjoy.com/json-pack/lib/msgpack';
 
/**
 * @category JSON Patch Extended
 */
export class OpFlip extends AbstractOp<'flip'> {
  public op() {
    return 'flip' as const;
  }
 
  public code() {
    return OPCODE.flip;
  }
 
  public apply(doc: unknown) {
    const ref = find(doc, this.path);
    if (ref.obj) (ref as any).obj[(ref as any).key] = !ref.val;
    else doc = !ref.val;
    return {doc, old: ref.val};
  }
 
  public toJson(parent?: AbstractOp): OperationFlip {
    const op: OperationFlip = {
      op: 'flip',
      path: formatJsonPointer(this.path),
    };
    return op;
  }
 
  public toCompact(parent: undefined | AbstractOp, verbose: boolean): CompactFlipOp {
    const opcode: OPCODE_FLIP = verbose ? 'flip' : OPCODE.flip;
    return [opcode, this.path];
  }
 
  public encode(encoder: IMessagePackEncoder, parent?: AbstractOp) {
    encoder.encodeArrayHeader(2);
    encoder.writer.u8(OPCODE.flip);
    encoder.encodeArray(this.path as unknown[]);
  }
}