json-joy
Version:
Collection of libraries for building collaborative editing apps.
57 lines (56 loc) • 1.88 kB
JavaScript
import { AbstractPredicateOp } from './AbstractPredicateOp';
import { find, formatJsonPointer } from '@jsonjoy.com/json-pointer';
import { OPCODE } from '../constants';
/**
* @category JSON Predicate
*/
export class OpEnds extends AbstractPredicateOp {
value;
ignore_case;
// tslint:disable-next-line variable-name
constructor(path, value, ignore_case) {
super(path);
this.value = value;
this.ignore_case = ignore_case;
}
op() {
return 'ends';
}
code() {
return OPCODE.ends;
}
test(doc) {
const { val } = find(doc, this.path);
if (typeof val !== 'string')
return false;
const outer = this.ignore_case ? val.toLowerCase() : val;
const inner = this.ignore_case ? this.value.toLowerCase() : this.value;
const test = outer.endsWith(inner);
return test;
}
toJson(parent) {
const op = {
op: 'ends',
path: formatJsonPointer(parent ? this.path.slice(parent.path.length) : this.path),
value: this.value,
};
if (this.ignore_case)
op.ignore_case = this.ignore_case;
return op;
}
toCompact(parent, verbose) {
const opcode = verbose ? 'ends' : OPCODE.ends;
return this.ignore_case
? [opcode, parent ? this.path.slice(parent.path.length) : this.path, this.value, 1]
: [opcode, parent ? this.path.slice(parent.path.length) : this.path, this.value];
}
encode(encoder, parent) {
const ignoreCase = this.ignore_case;
encoder.encodeArrayHeader(ignoreCase ? 4 : 3);
encoder.writer.u8(OPCODE.ends);
encoder.encodeArray(parent ? this.path.slice(parent.path.length) : this.path);
encoder.encodeString(this.value);
if (ignoreCase)
encoder.writer.u8(1);
}
}