UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

45 lines (44 loc) 1.47 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.applyPatch = applyPatch; const clone_1 = require("@jsonjoy.com/util/lib/json-clone/clone"); const v6_1 = require("@jsonjoy.com/json-pointer/lib/findByPointer/v6"); function applyOp(doc, operation) { switch (operation.op) { case 'add': { const [obj, key] = (0, v6_1.findByPointer)(operation.path, doc); switch (typeof key) { case 'number': { if (key > obj.length) throw new Error('INVALID_INDEX'); if (key === obj.length) obj.push(operation.value); else obj.splice(key, 0, operation.value); break; } case 'string': { obj[key] = operation.value; break; } default: { doc = operation.value; break; } } } } return { doc }; } function applyPatch(doc, patch, options) { if (!options.mutate) doc = (0, clone_1.clone)(doc); const res = []; for (let i = 0; i < patch.length; i++) { const operation = patch[i]; const operationResult = applyOp(doc, operation); res.push(operationResult); doc = operationResult.doc; } return { doc, res }; }