Implemented inverse patches
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parent 8aa82bb · Browse files · 2 files·+48 added−7 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+48 added−7 removed
- tests:+7 added−7 removed
- other:+41 added−0 removed
Provenance
- Commit
d203f56- Tree
fb6ce34- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
8aa82bb
2 files changed+48 added−7 removed
modified:__tests__/patch.js+7 added-7 removed
1223456778910113 unmodified lines15161718192019202122232424252627282930303132333435353637383979 unmodified lines"use strict"import produce, {setUseProxies} from "../src/immer"import produce, {setUseProxies, applyPatches} from "../src/immer"
jest.setTimeout(1000)
function runPatchTest(name, base, producer, patches) { function runPatchTest() { function runPatchTestHelper() { let recordedPatches let inversePatches const res = produce(base, producer, (p, i) => { recordedPatches = p3 unmodified lines test("produces the correct patches", () => { expect(recordedPatches).toEqual(patches) })
test.skip("patches are replayable", () => { expect(applyPatches(base, recordedPatches)).toBe(res) test("patches are replayable", () => { expect(applyPatches(base, recordedPatches)).toEqual(res) })
test.skip("patches can be revered", () => { expect(applyPatches(res, inversePatches)).toBe(base) expect(applyPatches(res, inversePatches)).toEqual(base) }) }
describe(`patches - ${name} - proxy`, () => { setUseProxies(true) runPatchTest() runPatchTestHelper() })
describe.skip(`patches - ${name} - es5`, () => { setUseProxies(false) runPatchTest() runPatchTestHelper() })}
runPatchTest(79 unmodified linesmodified:src/immer.js+41 added
58 unmodified lines59 return getUseProxies()60 ? produceProxy(baseState, producer, patchListener)61 : produceEs5(baseState, producer, patchListener)62 }63+64+export function applyPatches(base, patches) {65+ return produce(base, draft => {66+ debugger67+ for (let i = 0; i < patches.length; i++) {68+ const patch = patches[i]69+ if (patch.path.length === 0 && patch.op === "replace") {70+ draft = patch.value71+ } else {72+ const path = patch.path.slice()73+ const key = path.pop()74+ const base = path.reduce((current, part) => {75+ if (!current)76+ throw new Error(77+ "Cannot apply patch, path doesn't resolve: " +78+ patch.path.join("/")79+ )80+ return current[part]81+ }, draft)82+ if (!base)83+ throw new Error(84+ "Cannot apply patch, path doesn't resolve: " +85+ patch.path.join("/")86+ )87+ switch (patch.op) {88+ case "replace":89+ base[key] = patch.value90+ break91+ case "remove":92+ delete base[key]93+ break94+ default:95+ throw new Error(96+ "Unsupported patch operation: " + patch.op97+ )98+ }99+ }100+ }101+ return draft102+ })103+}