json-joy
Version:
Collection of libraries for building collaborative editing apps.
51 lines (50 loc) • 1.6 kB
JavaScript
import { AbstractPredicateOp } from './AbstractPredicateOp';
import { find, formatJsonPointer } from '@jsonjoy.com/json-pointer';
import { OPCODE } from '../constants';
const { isArray } = Array;
/**
* @category JSON Predicate
*/
export class OpTestType extends AbstractPredicateOp {
type;
constructor(path, type) {
super(path);
this.type = type;
}
op() {
return 'test_type';
}
code() {
return OPCODE.test_type;
}
test(doc) {
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) > -1)
return true;
if (typeof val === 'number' && val === Math.round(val) && this.type.indexOf('integer') > -1)
return true;
return false;
}
toJson(parent) {
const op = {
op: 'test_type',
path: formatJsonPointer(parent ? this.path.slice(parent.path.length) : this.path),
type: this.type,
};
return op;
}
toCompact(parent, verbose) {
const opcode = verbose ? 'test_type' : OPCODE.test_type;
return [opcode, parent ? this.path.slice(parent.path.length) : this.path, this.type];
}
encode(encoder, parent) {
encoder.encodeArrayHeader(3);
encoder.writer.u8(OPCODE.test_type);
encoder.encodeArray(parent ? this.path.slice(parent.path.length) : this.path);
encoder.encodeArray(this.type);
}
}