Skip to content
Myr

fix: don't unnecessary modify draft if replaying patches results in a new state anyway

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 7cd2dc1 · Browse files · 3 files+89 added−33 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+89 added−33 removed

  • tests:+45 added−1 removed
  • other:+44 added−32 removed

3 files+89 added−33 removed

modified:__tests__/patch.js+45 added-1 removed
454 unmodified lines
455 )456 const res = runPatchTest(457 {},458 d => {459 debugger459 applyPatches(d, [...p1, ...p2])460 },461 []462 )
20 unmodified lines
483 test("valid result", () => {484 expect(res).toEqual({})485 })486})487488test("replaying patches with interweaved replacements should work correctly", () => {489 const patches = []490 const s0 = {x: 1}491492 const s1 = produce(493 s0,494 draft => {495 draft.x = 2496 },497 p => {498 patches.push(...p)499 }500 )501502 const s2 = produce(503 s1,504 draft => {505 return {x: 0}506 },507 p => {508 patches.push(...p)509 }510 )511512 const s3 = produce(513 s2,514 draft => {515 draft.x--516 },517 p => {518 patches.push(...p)519 }520 )521522 expect(s3).toEqual({x: -1}) // correct result523 expect(applyPatches(s0, patches)).toEqual({x: -1}) // correct replay524525 // manual replay on a draft should also be correct526 expect(527 produce(s0, draft => {528 return applyPatches(draft, patches)529 })530 ).toEqual({x: -1})531})
modified:src/immer.js+15 added-2 removed
119 unmodified lines
120 this.useProxies = value121 assign(this, value ? modernProxy : legacyProxy)122 }123 applyPatches(base, patches) {124 // Mutate the base state when a draft is passed.124 // If a patch replaces the entire state, take that replacement as base125 // before applying patches126 let i127 for (i = patches.length - 1; i >= 0; i--) {128 const patch = patches[i]129 if (patch.path.length === 0 && patch.op === "replace") {130 base = patch.value131 break132 }133 }134135 if (isDraft(base)) {136 // N.B: never hits if some patch a replacement, patches are never drafts137 return applyPatches(base, patches)138 }139 // Otherwise, produce a copy of the base state.129 return this.produce(base, draft => applyPatches(draft, patches))140 return this.produce(base, draft =>141 applyPatches(draft, patches.slice(i + 1))142 )143 }144 /** @internal */145 processResult(result, scope) {146 const baseDraft = scope.drafts[0]
150 unmodified lines
modified:src/patches.js+29 added-30 removed