All files / json-patch/op OpIn.ts

95.45% Statements 21/22
100% Branches 9/9
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 56    15x 15x 15x   15x           15x     65x   65x       3x               15x 20x 10x       25x         25x       20x 20x       10x 10x 10x 10x      
import type {CompactInOp, OPCODE_IN} from '../codec/compact/types';
import type {OperationIn} from '../types';
import {find, type Path, formatJsonPointer} from '@jsonjoy.com/json-pointer';
import {AbstractPredicateOp} from './AbstractPredicateOp';
import {OPCODE} from '../constants';
import type {AbstractOp} from './AbstractOp';
import {deepEqual} from '@jsonjoy.com/util/lib/json-equal/deepEqual';
import type {IMessagePackEncoder} from '@jsonjoy.com/json-pack/lib/msgpack';
 
/**
 * @category JSON Predicate
 */
export class OpIn extends AbstractPredicateOp<'in'> {
  constructor(
    path: Path,
    public readonly value: unknown[],
  ) {
    super(path);
  }
 
  public op() {
    return 'in' as const;
  }
 
  public code() {
    return OPCODE.in;
  }
 
  public test(doc: unknown) {
    const {val} = find(doc, this.path);
    for (const x of this.value) if (deepEqual(val, x)) return true;
    return false;
  }
 
  public toJson(parent?: AbstractOp): OperationIn {
    const op: OperationIn = {
      op: 'in',
      path: formatJsonPointer(parent ? this.path.slice(parent.path.length) : this.path),
      value: this.value,
    };
    return op;
  }
 
  public toCompact(parent: undefined | AbstractOp, verbose: boolean): CompactInOp {
    const opcode: OPCODE_IN = verbose ? 'in' : OPCODE.in;
    return [opcode, parent ? this.path.slice(parent.path.length) : this.path, this.value];
  }
 
  public encode(encoder: IMessagePackEncoder, parent?: AbstractOp) {
    encoder.encodeArrayHeader(3);
    encoder.writer.u8(OPCODE.in);
    encoder.encodeArray(parent ? this.path.slice(parent.path.length) : (this.path as unknown[]));
    encoder.encodeArray(this.value);
  }
}