json-joy
Version:
Collection of libraries for building collaborative editing apps.
59 lines (58 loc) • 1.88 kB
JavaScript
import { AbstractPredicateOp } from './AbstractPredicateOp';
import { find, formatJsonPointer } from '@jsonjoy.com/json-pointer';
import { OPCODE } from '../constants';
/**
* @category JSON Patch Extended
*/
export class OpTestString extends AbstractPredicateOp {
pos;
str;
not;
constructor(path, pos, str, not) {
super(path);
this.pos = pos;
this.str = str;
this.not = not;
}
op() {
return 'test_string';
}
code() {
return OPCODE.test_string;
}
test(doc) {
const { val } = find(doc, this.path);
if (typeof val !== 'string')
return false;
const length = val.length;
const start = Math.min(this.pos, length);
const end = Math.min(this.pos + this.str.length, length);
const test = val.substring(start, end) === this.str;
return this.not ? !test : test;
}
toJson(parent) {
const op = {
op: 'test_string',
path: formatJsonPointer(parent ? this.path.slice(parent.path.length) : this.path),
pos: this.pos,
str: this.str,
};
if (this.not)
op.not = this.not;
return op;
}
toCompact(parent, verbose) {
const opcode = verbose ? 'test_string' : OPCODE.test_string;
const path = parent ? this.path.slice(parent.path.length) : this.path;
return this.not ? [opcode, path, this.pos, this.str, 1] : [opcode, path, this.pos, this.str];
}
encode(encoder, parent) {
encoder.encodeArrayHeader(this.not ? 5 : 4);
encoder.writer.u8(OPCODE.test_string);
encoder.encodeArray(parent ? this.path.slice(parent.path.length) : this.path);
encoder.encodeNumber(this.pos);
encoder.encodeString(this.str);
if (this.not)
encoder.writer.u8(1);
}
}