All files / json-patch/op OpTestType.ts

100% Statements 23/23
84.61% Branches 11/13
100% Functions 6/6
100% Lines 19/19

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  17x   17x 17x     17x         17x     102x   102x       18x       6x       72x 72x 64x 52x 20x 16x       15x         15x       12x 12x      
import type {CompactTestTypeOp, OPCODE_TEST_TYPE} from '../codec/compact/types';
import {AbstractPredicateOp} from './AbstractPredicateOp';
import type {OperationTestType, JsTypes, JsonPatchTypes} from '../types';
import {find, type Path, formatJsonPointer} from '@jsonjoy.com/json-pointer';
import {OPCODE} from '../constants';
import type {AbstractOp} from './AbstractOp';
 
const {isArray} = Array;
 
/**
 * @category JSON Predicate
 */
export class OpTestType extends AbstractPredicateOp<'test_type'> {
  constructor(
    path: Path,
    public readonly type: JsonPatchTypes[],
  ) {
    super(path);
  }
 
  public op() {
    return 'test_type' as const;
  }
 
  public code() {
    return OPCODE.test_type;
  }
 
  public test(doc: unknown): boolean {
    const {val} = find(doc, this.path);
    if (val === null) return this.type.indexOf('null') > -1;
    if (isArray(val)) return this.type.indexOf('array') > -1;
    if (this.type.indexOf(typeof val as JsTypes) > -1) return true;
    if (typeof val === 'number' && val === Math.round(val) && this.type.indexOf('integer') > -1) return true;
    return false;
  }
 
  public toJson(parent?: AbstractOp): OperationTestType {
    const op: OperationTestType = {
      op: 'test_type',
      path: formatJsonPointer(parent ? this.path.slice(parent.path.length) : this.path),
      type: this.type,
    };
    return op;
  }
 
  public toCompact(parent: undefined | AbstractOp, verbose: boolean): CompactTestTypeOp {
    const opcode: OPCODE_TEST_TYPE = verbose ? 'test_type' : OPCODE.test_type;
    return [opcode, parent ? this.path.slice(parent.path.length) : this.path, this.type];
  }
}