UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

56 lines (55 loc) 1.51 kB
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]; } encode(encoder) { encoder.encodeArrayHeader(3); encoder.writer.u8(OPCODE.add); encoder.encodeArray(this.path); encoder.encodeAny(this.value); } }