UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

52 lines (51 loc) 1.6 kB
import { AbstractPredicateOp } from './AbstractPredicateOp'; import { find, formatJsonPointer } from '@jsonjoy.com/json-pointer'; import { OPCODE } from '../constants'; const { isArray } = Array; /** * @category JSON Predicate */ export class OpType extends AbstractPredicateOp { value; constructor(path, value) { super(path); this.value = value; } op() { return 'type'; } code() { return OPCODE.type; } test(doc) { const { val } = find(doc, this.path); if (val === null) return this.value === 'null'; if (isArray(val)) return this.value === 'array'; // biome-ignore lint: comparison to value is on purpose if (typeof val === this.value) return true; if (typeof val === 'number' && val === Math.round(val) && this.value === 'integer') return true; return false; } toJson(parent) { const op = { op: 'type', path: formatJsonPointer(parent ? this.path.slice(parent.path.length) : this.path), value: this.value, }; return op; } toCompact(parent, verbose) { const opcode = verbose ? 'type' : OPCODE.type; return [opcode, parent ? this.path.slice(parent.path.length) : this.path, this.value]; } encode(encoder, parent) { encoder.encodeArrayHeader(3); encoder.writer.u8(OPCODE.type); encoder.encodeArray(parent ? this.path.slice(parent.path.length) : this.path); encoder.encodeString(this.value); } }