json-joy
Version:
Collection of libraries for building collaborative editing apps.
50 lines • 1.36 kB
JavaScript
import { AbstractOp } from './AbstractOp';
import { find, formatJsonPointer } from '@jsonjoy.com/json-pointer';
import { OPCODE } from '../constants';
import { clone as deepClone } from '@jsonjoy.com/util/lib/json-clone/clone';
/**
* @category JSON Patch
*/
export class OpAdd extends AbstractOp {
value;
constructor(path, value) {
super(path);
this.value = value;
}
op() {
return 'add';
}
code() {
return OPCODE.add;
}
apply(doc) {
const { val, key, obj } = find(doc, this.path);
const value = deepClone(this.value);
if (!obj)
doc = value;
else if (typeof key === 'string')
obj[key] = value;
else {
const length = obj.length;
if (key < length)
obj.splice(key, 0, value);
else if (key > length)
throw new Error('INVALID_INDEX');
else
obj.push(value);
}
return { doc, old: val };
}
toJson(parent) {
return {
op: 'add',
path: formatJsonPointer(this.path),
value: this.value,
};
}
toCompact(parent, verbose) {
const opcode = verbose ? 'add' : OPCODE.add;
return [opcode, this.path, this.value];
}
}
//# sourceMappingURL=OpAdd.js.map