diff --git a/__tests__/patch.js b/__tests__/patch.js index 32aa526d..4d6e65c5 100644 --- a/__tests__/patch.js +++ b/__tests__/patch.js @@ -249,9 +249,10 @@ describe("arrays - modify and shrink", () => { d.x[0] = 4 d.x.length = 2 }, + [{op: "replace", path: ["x", 0], value: 4}, {op: "remove", path: ["x", 2]}], [ - {op: "replace", path: ["x", 0], value: 4}, - {op: "replace", path: ["x", "length"], value: 2} + {op: "replace", path: ["x", 0], value: 1}, + {op: "add", path: ["x", 2], value: 3} ] ) }) @@ -290,7 +291,7 @@ describe("arrays - truncate", () => { d => { d.x.length -= 2 }, - [{op: "replace", path: ["x", "length"], value: 1}], + [{op: "remove", path: ["x", 2]}, {op: "remove", path: ["x", 1]}], [ {op: "add", path: ["x", 1], value: 2}, {op: "add", path: ["x", 2], value: 3} @@ -305,7 +306,7 @@ describe("arrays - pop twice", () => { d.x.pop() d.x.pop() }, - [{op: "replace", path: ["x", "length"], value: 1}] + [{op: "remove", path: ["x", 2]}, {op: "remove", path: ["x", 1]}] ) }) @@ -319,7 +320,7 @@ describe("arrays - push multiple", () => { {op: "add", path: ["x", 3], value: 4}, {op: "add", path: ["x", 4], value: 5} ], - [{op: "replace", path: ["x", "length"], value: 3}] + [{op: "remove", path: ["x", 4]}, {op: "remove", path: ["x", 3]}] ) }) @@ -361,6 +362,28 @@ describe("arrays - splice (shrink)", () => { ) }) +describe("arrays - splice should should result in remove op.", () => { + runPatchTest( + [1, 2], + d => { + d.splice(1, 1) + }, + [{op: "remove", path: [1]}], + [{op: "add", path: [1], value: 2}] + ) +}) + +describe("arrays - NESTED splice should should result in remove op.", () => { + runPatchTest( + {a: {b: {c: [1, 2]}}}, + d => { + d.a.b.c.splice(1, 1) + }, + [{op: "remove", path: ["a", "b", "c", 1]}], + [{op: "add", path: ["a", "b", "c", 1], value: 2}] + ) +}) + describe("simple replacement", () => { runPatchTest({x: 3}, _d => 4, [{op: "replace", path: [], value: 4}]) }) diff --git a/src/patches.js b/src/patches.js index 0d5b3d5e..03bda06f 100644 --- a/src/patches.js +++ b/src/patches.js @@ -47,7 +47,6 @@ function generateArrayPatches(state, basePath, patches, inversePatches) { } } - const useRemove = end != base.length const replaceCount = patches.length // Process added indices. @@ -58,20 +57,9 @@ function generateArrayPatches(state, basePath, patches, inversePatches) { path, value: copy[i] } - if (useRemove) { - inversePatches.push({ - op: "remove", - path - }) - } - } - - // One "replace" patch reverses all non-splicing "add" patches. - if (!useRemove) { inversePatches.push({ - op: "replace", - path: basePath.concat(["length"]), - value: base.length + op: "remove", + path }) } }