UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

59 lines (58 loc) 1.71 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OpAdd = void 0; const AbstractOp_1 = require("./AbstractOp"); const json_pointer_1 = require("@jsonjoy.com/json-pointer"); const constants_1 = require("../constants"); const clone_1 = require("@jsonjoy.com/util/lib/json-clone/clone"); /** * @category JSON Patch */ class OpAdd extends AbstractOp_1.AbstractOp { constructor(path, value) { super(path); this.value = value; } op() { return 'add'; } code() { return constants_1.OPCODE.add; } apply(doc) { const { val, key, obj } = (0, json_pointer_1.find)(doc, this.path); const value = (0, clone_1.clone)(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: (0, json_pointer_1.formatJsonPointer)(this.path), value: this.value, }; } toCompact(parent, verbose) { const opcode = verbose ? 'add' : constants_1.OPCODE.add; return [opcode, this.path, this.value]; } encode(encoder) { encoder.encodeArrayHeader(3); encoder.writer.u8(constants_1.OPCODE.add); encoder.encodeArray(this.path); encoder.encodeAny(this.value); } } exports.OpAdd = OpAdd;