Skip to content
Myr

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

2 files+48 added−7 removed

modified:__tests__/patch.js+7 added-7 removed
modified:src/immer.js+41 added
58 unmodified lines
59 return getUseProxies()60 ? produceProxy(baseState, producer, patchListener)61 : produceEs5(baseState, producer, patchListener)62}6364export 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}