You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Shrinking an array with length = and growing it back loses the patches for the truncated indices #1355
With enablePatches(), if a recipe shrinks a draft array by assigning .length and then grows it back to at least its original length, no replace patch (and no inverse patch) is produced for the truncated indices. Replaying the patches on the base gives a different state than the recipe, and the inverse patches do not restore the base. The same recipe written with splice(0) produces correct patches.
Link to repro
Not applicable: no CodeSandbox account; the script below and the unit test at the end reproduce it.
To Reproduce
npm i immer@11.2.9, save as t.mjs, run node t.mjs:
import{produceWithPatches,applyPatches,enablePatches}from"immer";enablePatches();constbase=[1];const[result,patches,inverse]=produceWithPatches(base,d=>{d.length=0;// truncate index 0d[1]=2;// grow again});console.log(result);console.log(patches);console.log(inverse);console.log(applyPatches(base,patches));console.log(applyPatches(result,inverse));const[r2,p2,i2]=produceWithPatches([1,2],d=>{d.length=0;d.length=2;});console.log(r2,p2,i2);
applyPatches(base, patches) keeps the stale 1 at index 0, and applyPatches(result, inverse) does not bring it back. The second recipe changes both elements but produces no patches at all.
Expected behavior
The same patches as for d.splice(0); d[1] = 2, which immer already gets right:
so that applyPatches(base, patches) gives [ undefined, 2 ] and applyPatches(result, inverse) gives [ 1 ].
generateArrayPatches_ in src/plugins/patches.ts only emits a replace for an index below base.length when assigned_.get(i) is set (or allIndicesReassigned_). Assigning a smaller length truncates copy_ without marking the dropped indices as assigned, so they are skipped once the array is long again.
Unit test:
test("length shrink then grow produces replace patches",()=>{constbase=[1]const[result,patches,inverse]=produceWithPatches(base,d=>{d.length=0d[1]=2})expect(applyPatches(base,patches)).toEqual(result)expect(applyPatches(result,inverse)).toEqual(base)})
Environment
We only accept bug reports against the latest Immer version.
Immer version: 11.2.9 (also main 75a290e, built from source), Node.js v26.13.0
I filed this report against the latest version of Immer
Activity