All files / json-patch/op OpDefined.ts

100% Statements 13/13
66.66% Branches 4/6
100% Functions 5/5
100% Lines 13/13

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  17x   17x 17x           17x   7x       6x       34x 29x 29x       15x       15x       12x 12x      
import type {CompactDefinedOp, OPCODE_DEFINED} from '../codec/compact/types';
import {AbstractPredicateOp} from './AbstractPredicateOp';
import type {OperationDefined} from '../types';
import {find, type Path, formatJsonPointer} from '@jsonjoy.com/json-pointer';
import {OPCODE} from '../constants';
import type {AbstractOp} from './AbstractOp';
 
/**
 * @category JSON Predicate
 */
export class OpDefined extends AbstractPredicateOp<'defined'> {
  public op() {
    return 'defined' as const;
  }
 
  public code() {
    return OPCODE.defined;
  }
 
  public test(doc: unknown) {
    const {val} = find(doc, this.path);
    const test = val !== undefined;
    return test;
  }
 
  public toJson(parent?: AbstractOp): OperationDefined {
    const op: OperationDefined = {
      op: 'defined',
      path: formatJsonPointer(parent ? this.path.slice(parent.path.length) : this.path),
    };
    return op;
  }
 
  public toCompact(parent: undefined | AbstractOp, verbose: boolean): CompactDefinedOp {
    const opcode: OPCODE_DEFINED = verbose ? 'defined' : OPCODE.defined;
    return [opcode, parent ? this.path.slice(parent.path.length) : this.path];
  }
}