json-joy
Version:
Collection of libraries for building collaborative editing apps.
54 lines (53 loc) • 1.65 kB
JavaScript
import { find, formatJsonPointer } from '@jsonjoy.com/json-pointer';
import { AbstractPredicateOp } from './AbstractPredicateOp';
import { OPCODE } from '../constants';
import { deepEqual } from '@jsonjoy.com/util/lib/json-equal/deepEqual';
/**
* @category JSON Patch
* @category JSON Predicate
*/
export class OpTest extends AbstractPredicateOp {
value;
not;
constructor(path, value, not) {
super(path);
this.value = value;
this.not = not;
}
op() {
return 'test';
}
code() {
return OPCODE.test;
}
test(doc) {
const { val } = find(doc, this.path);
if (val === undefined)
return !!this.not;
const test = deepEqual(val, this.value);
return this.not ? !test : test;
}
toJson(parent) {
const op = {
op: 'test',
path: formatJsonPointer(parent ? this.path.slice(parent.path.length) : this.path),
value: this.value,
};
if (this.not)
op.not = this.not;
return op;
}
toCompact(parent, verbose) {
const path = parent ? this.path.slice(parent.path.length) : this.path;
const opcode = verbose ? 'test' : OPCODE.test;
return this.not ? [opcode, path, this.value, 1] : [opcode, path, this.value];
}
encode(encoder, parent) {
encoder.encodeArrayHeader(this.not ? 4 : 3);
encoder.writer.u8(OPCODE.test);
encoder.encodeArray(parent ? this.path.slice(parent.path.length) : this.path);
encoder.encodeAny(this.value);
if (this.not)
encoder.writer.u8(1);
}
}