From 67fa28b3e0f57a776e4577b956f2c8f51f252871 Mon Sep 17 00:00:00 2001 From: unadlib Date: Mon, 26 Oct 2026 08:29:12 -0700 Subject: [PATCH 01/13] fix: leave an array draft unchanged when deleting an index it does not have --- src/draft.ts | 5 ++ test/assign-undefined.test.ts | 88 ++++++++++++++++++++++++++++++++++- 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/src/draft.ts b/src/draft.ts index 0551b844..95d9fcb5 100644 --- a/src/draft.ts +++ b/src/draft.ts @@ -322,6 +322,11 @@ function definePropertyTrap(): never { function deletePropertyTrap(target: ProxyDraft, key: string | symbol) { if (target.type === DraftType.Array) { + // A deleted index holds `undefined` afterwards. Deleting an index the + // array does not have changes nothing, as in JavaScript; assigning + // `undefined` to it would lengthen an array that the recipe shortened. + // Other keys reach the set trap, which rejects them. + if (!hasOwn.call(latest(target), key) && isArrayIndexKey(key)) return true; return setTrap(target, key, undefined); } if (target.original[key] !== undefined || key in target.original) { diff --git a/test/assign-undefined.test.ts b/test/assign-undefined.test.ts index 4800e709..c1ff12ff 100644 --- a/test/assign-undefined.test.ts +++ b/test/assign-undefined.test.ts @@ -1,6 +1,6 @@ import { apply, create } from '../src'; -const shape = (array: unknown[]) => ({ +const shape = (array: readonly unknown[]) => ({ length: array.length, own: Array.from(array, (_value, index) => index in array), }); @@ -64,3 +64,89 @@ describe('assigning undefined to a removed key', () => { expect(state).toBe(base); }); }); + +// Deleting an array index assigns `undefined` to it, but deleting an index +// that the array does not have changes nothing, as in plain JS. +describe('deleting an array index the draft does not have', () => { + const cases: [string, unknown[], (list: unknown[]) => void][] = [ + [ + 'pop', + ['y', 'y'], + (list) => { + list.pop(); + delete list[1]; + }, + ], + [ + 'length', + [null, null], + (list) => { + list.length = 0; + delete list[1]; + }, + ], + [ + 'shift', + [1, 2, 3], + (list) => { + list.shift(); + delete list[2]; + }, + ], + [ + 'splice', + [1, 2, 3], + (list) => { + list.splice(1); + delete list[2]; + }, + ], + ]; + + test.each(cases)( + 'leaves an array shortened by %s short', + (_name, items, recipe) => { + const expected = items.slice(); + recipe(expected); + for (const enableAutoFreeze of [false, true]) { + const base = { list: items.slice() }; + const [state, patches, inverse] = create( + base, + (draft) => recipe(draft.list), + { enablePatches: true, enableAutoFreeze } + ); + expect(shape(state.list)).toStrictEqual(shape(expected)); + expect(state.list).toStrictEqual(expected); + expect(apply(base, patches)).toStrictEqual(state); + expect(apply(state, inverse)).toStrictEqual(base); + } + } + ); + + test('changes nothing at a hole or past the end', () => { + const list = [1, 2, 3]; + delete list[1]; + const base = { list }; + const state = create(base, (draft) => { + delete draft.list[1]; + delete draft.list[5]; + }); + expect(state).toBe(base); + }); + + test('still assigns undefined to an index the array has', () => { + const base = [1, 2, 3]; + const [state, patches, inverse] = create( + base, + (draft) => { + draft.pop(); + delete draft[1]; + }, + { enablePatches: true } + ); + expect(shape(state)).toStrictEqual({ length: 2, own: [true, true] }); + expect(state).toStrictEqual([1, undefined]); + expect(apply(base, patches)).toStrictEqual(state); + expect(apply(state, inverse)).toStrictEqual(base); + }); +}); From b9804590d61d4537f892932f226972c524124ce8 Mon Sep 17 00:00:00 2001 From: unadlib Date: Mon, 26 Oct 2026 08:33:32 -0700 Subject: [PATCH 02/13] build: refresh the size baseline for deleting missing array indices --- scripts/build-size-baseline.json | 84 ++++++++++++++++---------------- 1 file changed, 42 insertions(+), 42 deletions(-) diff --git a/scripts/build-size-baseline.json b/scripts/build-size-baseline.json index c2a1e45d..96aeb20e 100644 --- a/scripts/build-size-baseline.json +++ b/scripts/build-size-baseline.json @@ -1,8 +1,8 @@ { "reference": { - "revision": "22e7114d920186a0b752dade2ac3bd3b7a74fca5", - "description": "A repeated moved array element is searched for with doubling steps and backward from the first step past its last copy", - "node": "v24.16.0", + "revision": "4f58b62296df553e411bb756ea0263d8d65fc21f", + "description": "Deleting an index that an array draft does not have changes nothing", + "node": "v24.22.0", "commands": [ "pnpm install --frozen-lockfile", "pnpm build" @@ -15,69 +15,69 @@ "esbuild": "0.24.0", "measurements": { "artifact/mutative.cjs.production.min.js": { - "raw": 27437, - "gzip": 9226, - "brotli": 8472 + "raw": 27470, + "gzip": 9242, + "brotli": 8489 }, "artifact/mutative.umd.production.min.js": { - "raw": 27592, - "gzip": 9292, - "brotli": 8515 + "raw": 27625, + "gzip": 9307, + "brotli": 8532 }, "artifact/mutative.esm.production.min.mjs": { - "raw": 27409, - "gzip": 9252, - "brotli": 8492 + "raw": 27442, + "gzip": 9266, + "brotli": 8508 }, "artifact/mutative.cjs.development.js": { - "raw": 73119, - "gzip": 17810, - "brotli": 15473 + "raw": 73224, + "gzip": 17836, + "brotli": 15475 }, "artifact/mutative.umd.development.js": { - "raw": 75403, - "gzip": 18014, - "brotli": 15646 + "raw": 75511, + "gzip": 18038, + "brotli": 15647 }, "artifact/mutative.esm.js": { - "raw": 73954, - "gzip": 17904, - "brotli": 15526 + "raw": 74059, + "gzip": 17927, + "brotli": 15549 }, "artifact/mutative.esm.mjs": { - "raw": 73955, - "gzip": 17906, - "brotli": 15527 + "raw": 74060, + "gzip": 17929, + "brotli": 15549 }, "consumer/import/create": { - "raw": 24594, - "gzip": 8609, - "brotli": 7924 + "raw": 24620, + "gzip": 8628, + "brotli": 7936 }, "consumer/import/patches": { - "raw": 26657, - "gzip": 9313, - "brotli": 8550 + "raw": 26683, + "gzip": 9329, + "brotli": 8557 }, "consumer/import/all": { - "raw": 27442, - "gzip": 9576, - "brotli": 8778 + "raw": 27468, + "gzip": 9588, + "brotli": 8793 }, "consumer/require/create": { - "raw": 26936, - "gzip": 9556, - "brotli": 8749 + "raw": 26968, + "gzip": 9564, + "brotli": 8762 }, "consumer/require/patches": { - "raw": 27004, - "gzip": 9591, - "brotli": 8792 + "raw": 27036, + "gzip": 9602, + "brotli": 8801 }, "consumer/require/all": { - "raw": 26901, - "gzip": 9534, - "brotli": 8777 + "raw": 26933, + "gzip": 9543, + "brotli": 8768 } } } From 71f4ce9e68181c7ff1ddba684f63847aeebde069 Mon Sep 17 00:00:00 2001 From: unadlib Date: Mon, 26 Oct 2026 09:16:24 -0700 Subject: [PATCH 03/13] test: check that an array draft still rejects deleting a key that is not an index --- test/assign-undefined.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/assign-undefined.test.ts b/test/assign-undefined.test.ts index c1ff12ff..3bd5e909 100644 --- a/test/assign-undefined.test.ts +++ b/test/assign-undefined.test.ts @@ -134,6 +134,14 @@ describe('deleting an array index the draft does not have', () => { expect(state).toBe(base); }); + test('still rejects a key that is not an index', () => { + expect(() => + create({ list: [1] }, (draft) => { + delete (draft.list as any).foo; + }) + ).toThrow("Only supports setting array indices and the 'length' property."); + }); + test('still assigns undefined to an index the array has', () => { const base = [1, 2, 3]; const [state, patches, inverse] = create( From b25ffc711d09ae4091175c3b54fa7312335aa314 Mon Sep 17 00:00:00 2001 From: unadlib Date: Tue, 27 Oct 2026 01:45:18 +0800 Subject: [PATCH 04/13] fix: preserve sparse array holes in forward and inverse patches --- docs/type-aliases/PatchesOptions.md | 2 + src/array.ts | 12 +- src/interface.ts | 2 + src/patch.ts | 121 +++- test/__snapshots__/apply.test.ts.snap | 56 +- test/apply.test.ts | 4 +- test/sparse-array-patches.test.ts | 521 ++++++++++++++++++ .../content/docs/advanced-guides/patches.mdx | 27 +- 8 files changed, 666 insertions(+), 79 deletions(-) create mode 100644 test/sparse-array-patches.test.ts diff --git a/docs/type-aliases/PatchesOptions.md b/docs/type-aliases/PatchesOptions.md index 1deca4d0..53628ff7 100644 --- a/docs/type-aliases/PatchesOptions.md +++ b/docs/type-aliases/PatchesOptions.md @@ -24,6 +24,8 @@ does not. Whether an array that gets shorter gets a `replace` patch of its `length`, as by default, or a `remove` patch for each index that it loses, as JSON Patch requires. +Recreating holes in a sparse array still uses length patches; +JSON cannot represent holes. ### pathAsArray? diff --git a/src/array.ts b/src/array.ts index 0f6e4dc6..80b79607 100644 --- a/src/array.ts +++ b/src/array.ts @@ -111,12 +111,12 @@ function arrayState(target: ProxyDraft) { }); } -// Holes are the one thing a move cannot replay through patches, so moving -// methods leave sparse arrays to the proxy. A hole reads as `undefined`, so an -// array in which the `includes` builtin finds no `undefined` has none; that -// scan is fast for every kind of array. Only arrays that hold `undefined` are -// checked index by index with `in`, the HasProperty check of the native -// algorithms, which costs several times more per element once many array +// Moving methods leave sparse arrays to the proxy, where deleting a present +// index assigns undefined; patches rebuild changed holes separately. A hole +// reads as `undefined`, so an array in which the `includes` builtin finds no +// `undefined` has none; that scan is fast for every kind of array. Arrays that +// hold `undefined` are checked index by index with `in`, the HasProperty check +// of the native algorithms, which costs several times more per element once many array // shapes have passed through it. Elements that are `undefined` are ordinary // values and move natively. function hasHoles(array: any[]) { diff --git a/src/interface.ts b/src/interface.ts index 46f48930..0d05ed0d 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -31,6 +31,8 @@ export type PatchesOptions = * Whether an array that gets shorter gets a `replace` patch of its * `length`, as by default, or a `remove` patch for each index that it * loses, as JSON Patch requires. + * Recreating holes in a sparse array still uses length patches; + * JSON cannot represent holes. */ arrayLengthAssignment?: boolean; }; diff --git a/src/patch.ts b/src/patch.ts index 540bb59d..7b9aee2a 100644 --- a/src/patch.ts +++ b/src/patch.ts @@ -21,6 +21,63 @@ function cloneIfNeeded(target: T): T { return proxyDraft.operated ? current(target as any) : proxyDraft.original; } +const hasOwn = Object.prototype.hasOwnProperty; + +// Index patches carry values, so neither an undefined value nor an index +// removal can represent a hole. Rebuild the affected suffix in each direction: +// truncate it, grow the length to leave holes, then restore only own indices. +// Keeping the array itself supports mutable application and arrays inside Sets. +function generateSparseArrayPatches( + original: any[], + copy: any[], + start: number, + basePath: any[], + patches: Patches, + inversePatches: Patches, + pathAsArray: boolean, + arrayLengthAssignment: boolean +) { + const lengthPath = escapePath(basePath.concat(['length']), pathAsArray); + const rebuild = (from: any[], to: any[], result: Patches) => { + const cut = Math.min(start, to.length); + if (arrayLengthAssignment) { + if (from.length > cut) { + result.push({ op: Operation.Replace, path: lengthPath, value: cut }); + } + } else { + for (let index = from.length - 1; index >= cut; index -= 1) { + result.push({ + op: Operation.Remove, + path: escapePath(basePath.concat([index]), pathAsArray), + }); + } + } + // JSON cannot encode holes. Growing a sparse array needs a length patch + // even when shrinking arrays use per-index removals. + if (to.length > cut) { + result.push({ + op: Operation.Replace, + path: lengthPath, + value: to.length, + }); + } + // Enumerate own indices instead of walking potentially huge gaps. Include + // non-enumerable indices too, but not length or custom array properties. + for (const key of Object.getOwnPropertyNames(to)) { + const index = Number(key); + if (index >= start && index < to.length && String(index) === key) { + result.push({ + op: Operation.Replace, + path: escapePath(basePath.concat([index]), pathAsArray), + value: cloneIfNeeded(to[index]), + }); + } + } + }; + rebuild(original, copy, patches); + rebuild(copy, original, inversePatches); +} + function generateArrayPatches( proxyState: ProxyDraft>, basePath: any[], @@ -30,6 +87,7 @@ function generateArrayPatches( ) { let { original, assignedMap, options } = proxyState; let copy = proxyState.copy!; + const { arrayLengthAssignment = true } = options.enablePatches; if (copy.length < original.length) { [original, copy] = [copy, original]; [patches, inversePatches] = [inversePatches, patches]; @@ -63,37 +121,68 @@ function generateArrayPatches( indices.push(assigned[position]); for (let position = 0; position < indices.length; position += 1) { const index = indices[position]; - // As the set trap compares, so 0 and -0 differ and NaN equals itself. - if (index < original.length && !isEqual(copy[index], original[index])) { - const _path = basePath.concat([index]); - const path = escapePath(_path, pathAsArray); - patches.push({ - op: Operation.Replace, - path, - value: cloneIfNeeded(copy[index]), - }); - inversePatches.push({ - op: Operation.Replace, - path, - value: cloneIfNeeded(original[index]), - }); + if (index < original.length) { + const value = copy[index]; + const previous = original[index]; + if ( + (value === undefined || previous === undefined) && + hasOwn.call(copy, index) !== hasOwn.call(original, index) + ) { + return generateSparseArrayPatches( + original, + copy, + index, + basePath, + patches, + inversePatches, + pathAsArray, + arrayLengthAssignment + ); + } + // As the set trap compares, so 0 and -0 differ and NaN equals itself. + if (!isEqual(value, previous)) { + const _path = basePath.concat([index]); + const path = escapePath(_path, pathAsArray); + patches.push({ + op: Operation.Replace, + path, + value: cloneIfNeeded(value), + }); + inversePatches.push({ + op: Operation.Replace, + path, + value: cloneIfNeeded(previous), + }); + } } } for (let index = original.length; index < copy.length; index += 1) { + const value = copy[index]; + if (value === undefined && !hasOwn.call(copy, index)) { + return generateSparseArrayPatches( + original, + copy, + index, + basePath, + patches, + inversePatches, + pathAsArray, + arrayLengthAssignment + ); + } const _path = basePath.concat([index]); const path = escapePath(_path, pathAsArray); patches.push({ op: Operation.Add, path, // If it is a draft, it needs to be deep cloned, and it may also be non-draft. - value: cloneIfNeeded(copy[index]), + value: cloneIfNeeded(value), }); } if (original.length < copy.length) { // https://www.rfc-editor.org/rfc/rfc6902#appendix-A.4 // For performance, here we only generate an operation that replaces the length of the array, // which is inconsistent with JSON Patch specification - const { arrayLengthAssignment = true } = options.enablePatches; if (arrayLengthAssignment) { const _path = basePath.concat(['length']); const path = escapePath(_path, pathAsArray); diff --git a/test/__snapshots__/apply.test.ts.snap b/test/__snapshots__/apply.test.ts.snap index efa26827..6d48a7a9 100644 --- a/test/__snapshots__/apply.test.ts.snap +++ b/test/__snapshots__/apply.test.ts.snap @@ -13716,63 +13716,15 @@ exports[`array 3`] = ` "value": undefined, }, { - "op": "add", - "path": [ - "arr9", - 3, - ], - "value": undefined, - }, - { - "op": "add", - "path": [ - "arr9", - 4, - ], - "value": undefined, - }, - { - "op": "add", - "path": [ - "arr9", - 5, - ], - "value": undefined, - }, - { - "op": "add", - "path": [ - "arr9", - 6, - ], - "value": undefined, - }, - { - "op": "add", - "path": [ - "arr9", - 7, - ], - "value": undefined, - }, - { - "op": "add", - "path": [ - "arr9", - 8, - ], - "value": undefined, - }, - { - "op": "add", + "op": "replace", "path": [ "arr9", - 9, + "length", ], - "value": undefined, + "value": 11, }, { - "op": "add", + "op": "replace", "path": [ "arr9", 10, diff --git a/test/apply.test.ts b/test/apply.test.ts index 94f674c5..77b68deb 100644 --- a/test/apply.test.ts +++ b/test/apply.test.ts @@ -48,9 +48,9 @@ function checkPatches(data: T, fn: (checkPatches: T) => void) { expect(patches).toMatchSnapshot(); expect(inversePatches).toMatchSnapshot(); const prevState = apply(state, inversePatches); - expect(prevState).toEqual(data); + expect(prevState).toStrictEqual(data); const nextState = apply(data as any, patches); - expect(nextState).toEqual(state); + expect(nextState).toStrictEqual(state); } test('array', () => { diff --git a/test/sparse-array-patches.test.ts b/test/sparse-array-patches.test.ts new file mode 100644 index 00000000..bbb2da19 --- /dev/null +++ b/test/sparse-array-patches.test.ts @@ -0,0 +1,521 @@ +/* eslint-disable no-sparse-arrays, no-bitwise */ +import jsonPatch from 'fast-json-patch'; +import { apply, create, type PatchesOptions } from '../src'; + +const modes = [ + { pathAsArray: true, arrayLengthAssignment: true }, + { pathAsArray: false, arrayLengthAssignment: true }, + { pathAsArray: true, arrayLengthAssignment: false }, + { pathAsArray: false, arrayLengthAssignment: false }, +] satisfies PatchesOptions[]; + +const cases: [string, () => any[], (draft: any[]) => void][] = [ + [ + 'unshift a trailing hole', + () => [1, ,], + (draft) => { + draft.unshift(0); + }, + ], + [ + 'splice before trailing holes', + () => [1, , ,], + (draft) => { + draft.splice(1, 0, 2); + }, + ], + [ + 'shift a leading hole', + () => [, 1, ,], + (draft) => { + draft.shift(); + }, + ], + [ + 'pop a trailing hole', + () => [1, ,], + (draft) => { + draft.pop(); + }, + ], + [ + 'truncate holes', + () => [1, , 2, ,], + (draft) => { + draft.length = 1; + }, + ], + [ + 'clear a sparse array', + () => [1, , 2, ,], + (draft) => { + draft.length = 0; + }, + ], + [ + 'grow length', + () => [1], + (draft) => { + draft.length = 4; + }, + ], + [ + 'assign beyond length', + () => [], + (draft) => { + draft[3] = 1; + }, + ], + [ + 'append then create a gap', + () => [1], + (draft) => { + draft.push(2); + draft[4] = 3; + }, + ], + [ + 'fill a hole with undefined', + () => [,], + (draft) => { + draft[0] = undefined; + }, + ], + [ + 'fill a hole with an object', + () => [,], + (draft) => { + draft[0] = { value: 1 }; + }, + ], + [ + 'remove and re-expose an element', + () => [1, 2, 3], + (draft) => { + draft.length = 1; + draft.length = 3; + }, + ], + [ + 'remove and re-expose undefined', + () => [undefined], + (draft) => { + draft.length = 0; + draft.length = 1; + }, + ], + [ + 'reverse holes', + () => [1, , , 2], + (draft) => { + draft.reverse(); + }, + ], + [ + 'sort holes', + () => [2, , 1, ,], + (draft) => { + draft.sort(); + }, + ], + [ + 'copyWithin holes', + () => [1, , , 2], + (draft) => { + draft.copyWithin(1, 2); + }, + ], + [ + 'fill holes', + () => [1, , , 2], + (draft) => { + draft.fill(undefined, 1, 3); + }, + ], + [ + 'nested change before a gap', + () => [{ value: 1 }], + (draft) => { + draft[0].value++; + draft.length = 3; + }, + ], + [ + 'nested change after a hole', + () => [, { value: 1 }], + (draft) => { + draft[1].value++; + draft[0] = undefined; + }, + ], + [ + 'move a changed child', + () => [{ value: 1 }, ,], + (draft) => { + draft[0].value++; + draft.unshift(0); + }, + ], + [ + 'drop a changed child', + () => [{ value: 1 }, ,], + (draft) => { + draft[0].value++; + draft.length = 0; + draft.length = 2; + }, + ], + [ + 'change a nested sparse array', + () => [[1, ,], ,], + (draft) => { + draft[0].unshift(0); + draft.unshift(2); + }, + ], +]; + +const mapKey = { id: 'array' }; +const containers: [string, (array: any[]) => any, (state: any) => any[]][] = [ + ['root', (array) => array, (state) => state], + ['object', (array) => ({ 'a/b~c': array }), (state) => state['a/b~c']], + ['array', (array) => [array], (state) => state[0]], + [ + 'Map', + (array) => new Map([['array', array]]), + (state) => state.get('array'), + ], + ['Set', (array) => new Set([array]), (state) => [...state][0]], +]; + +describe.each(cases)('sparse patches: %s', (_name, make, recipe) => { + test.each(containers)('round trips in a %s', (_container, wrap, read) => { + for (const enablePatches of modes) { + for (const enableAutoFreeze of [false, true]) { + const base = wrap(make()); + const before = wrap(make()); + const [state, patches, inverse] = create( + base, + (draft: any) => recipe(read(draft)), + { enablePatches, enableAutoFreeze } + ); + expect(base).toStrictEqual(before); + expect(state).toStrictEqual( + create(wrap(make()), (draft: any) => recipe(read(draft)), { + enableAutoFreeze, + }) + ); + const replay = apply(base, patches); + expect(replay).toStrictEqual(state); + expect(apply(state, inverse)).toStrictEqual(before); + expect(apply(replay, inverse)).toStrictEqual(before); + expect(apply(apply(state, inverse), patches)).toStrictEqual(state); + + // Mutable application and application on a live draft must keep the + // same root; array replacement patches would not support these cases. + const mutable = wrap(make()); + apply(mutable, patches, { mutable: true }); + expect(mutable).toStrictEqual(state); + apply(mutable, inverse, { mutable: true }); + expect(mutable).toStrictEqual(before); + expect( + create(wrap(make()), (draft: any) => { + expect(apply(draft, patches)).toBe(draft); + }) + ).toStrictEqual(state); + } + } + }); +}); + +test('preserves array holes as well as explicit undefined', () => { + const [state, patches, inverse] = create( + [1, ,], + (draft) => { + draft.unshift(0); + }, + { enablePatches: true } + ); + expect(Object.hasOwn(state, 2)).toBe(false); + expect(Object.hasOwn(apply([1, ,], patches), 2)).toBe(false); + expect(Object.hasOwn(apply(state, inverse), 1)).toBe(false); + + const [filled, fill, undo] = create( + [,], + (draft) => { + draft[0] = undefined; + }, + { enablePatches: true } + ); + expect(Object.hasOwn(filled, 0)).toBe(true); + expect(Object.hasOwn(apply([,], fill), 0)).toBe(true); + expect(Object.hasOwn(apply(filled, undo), 0)).toBe(false); +}); + +test('keeps unchanged prefix references and supports object Map keys', () => { + const item = { value: 1 }; + const array = [item, ,]; + const base = new Map([[mapKey, array]]); + const [state, patches, inverse] = create( + base, + (draft) => { + draft.get(mapKey)!.length = 4; + }, + { enablePatches: true } + ); + const replay = apply(base, patches); + expect(replay).toStrictEqual(state); + expect(replay.get(mapKey)![0]).toBe(item); + expect(apply(replay, inverse)).toStrictEqual(base); +}); + +test('deleting a missing index remains a no-op with empty patches', () => { + const base = [1, ,]; + const [state, patches, inverse] = create( + base, + (draft) => { + delete draft[1]; + delete draft[9]; + }, + { enablePatches: true } + ); + expect(state).toBe(base); + expect(patches).toStrictEqual([]); + expect(inverse).toStrictEqual([]); +}); + +test('per-index removal mode uses length patches only to grow sparse arrays', () => { + const base = [1, , 2, ,]; + const [state, patches, inverse] = create( + base, + (draft) => { + draft.splice(0, 2); + draft.length = 5; + }, + { enablePatches: { arrayLengthAssignment: false } } + ); + for (const [input, steps] of [ + [base, patches], + [state, inverse], + ] as const) { + const target = input.slice(); + for (const patch of steps) { + if (patch.path[patch.path.length - 1] === 'length') { + expect(patch.value).toBeGreaterThan(target.length); + } + apply(target, [patch], { mutable: true }); + } + } +}); + +test('dense JSON arrays retain interoperable index patches', () => { + const base = [1, 2, 3]; + const [state, patches, inverse] = create( + base, + (draft) => { + draft.unshift(0); + draft.splice(2, 2); + }, + { enablePatches: { pathAsArray: false, arrayLengthAssignment: false } } + ); + expect( + jsonPatch.applyPatch(base.slice(), patches as any, true).newDocument + ).toStrictEqual(state); + expect( + jsonPatch.applyPatch(state.slice(), inverse as any, true).newDocument + ).toStrictEqual(base); + expect( + [...patches, ...inverse].some((patch) => patch.path.endsWith('/length')) + ).toBe(false); +}); + +test('large gaps need patches only for lengths and present indices', () => { + const [state, patches, inverse] = create( + [] as number[], + (draft) => { + draft[100_000] = 1; + }, + { enablePatches: true } + ); + expect(patches.length).toBeLessThanOrEqual(3); + expect(inverse.length).toBe(1); + const replay = apply([], patches); + expect(replay.length).toBe(state.length); + expect(Object.keys(replay)).toStrictEqual(['100000']); + expect(replay[100_000]).toBe(1); + expect(apply(replay, inverse)).toStrictEqual([]); +}); + +test('rebuilds non-enumerable array indices too', () => { + const base = new Array(4); + Object.defineProperty(base, '3', { value: 9, configurable: true }); + const [state, patches, inverse] = create( + base, + (draft) => { + draft[0] = 1; + }, + { enablePatches: true } + ); + expect(apply(base, patches)).toStrictEqual(state); + const restored = apply(state, inverse); + expect(restored.length).toBe(4); + expect(Object.hasOwn(restored, 0)).toBe(false); + expect(Object.hasOwn(restored, 3)).toBe(true); + expect(restored[3]).toBe(9); +}); + +test('manual, async and nested producers preserve sparse patches', async () => { + for (const enablePatches of modes) { + const base = [1, ,]; + const [draft, finish] = create(base, { enablePatches }); + draft.unshift(0); + const [state, patches, inverse] = finish(); + expect(apply(base, patches)).toStrictEqual(state); + expect(apply(state, inverse)).toStrictEqual(base); + const [asyncState, asyncPatches, asyncInverse] = await create( + base, + async (inner) => { + await Promise.resolve(); + inner.unshift(0); + }, + { enablePatches } + ); + expect(apply(base, asyncPatches)).toStrictEqual(asyncState); + expect(apply(asyncState, asyncInverse)).toStrictEqual(base); + expect( + create({ list: base }, (outer) => { + const [next, forward, backward] = create( + outer.list, + (inner) => { + inner.unshift(0); + }, + { enablePatches } + ); + expect(apply(base, forward)).toStrictEqual(next); + expect(apply(next, backward)).toStrictEqual(base); + outer.list = next; + }) + ).toStrictEqual({ list: state }); + } +}); + +test('array subclasses and marked arrays use the same sparse replay contract', () => { + class Items extends Array {} + for (const mark of [undefined, () => 'immutable' as const]) { + const base = new Items(3); + base[0] = 1; + const [state, patches, inverse] = create( + base, + (draft) => { + draft.unshift(0); + draft[2] = undefined; + }, + { enablePatches: true, mark } + ); + expect(state).toBeInstanceOf(Items); + expect(apply(base, patches, { mark })).toStrictEqual(state); + expect(apply(state, inverse, { mark })).toStrictEqual(base); + } +}); + +test('random sparse edits preserve values, own indices and repeated undo/redo', () => { + let seed = 0x54729; + const random = (limit: number) => { + seed ^= seed << 13; + seed ^= seed >>> 17; + seed ^= seed << 5; + return (seed >>> 0) % limit; + }; + const value = () => + [undefined, null, 0, -0, NaN, 1, 2, { value: 1 }][random(8)]; + for (let sample = 0; sample < 1500; sample += 1) { + const base = Array.from({ length: random(8) }, value); + for (let index = 0; index < base.length; index += 1) { + if (random(3) === 0) delete base[index]; + } + const before = structuredClone(base); + const operations = Array.from({ length: 1 + random(8) }, () => ({ + code: random(14), + a: random(9), + b: random(9), + value: value(), + })); + const recipe = (draft: any[]) => { + for (const { code, a, b, value } of operations) { + const item = structuredClone(value); + switch (code) { + case 0: + delete draft[a]; + break; + case 1: + draft[a] = item; + break; + case 2: + draft.length = a; + break; + case 3: + draft.push(item); + break; + case 4: + draft.pop(); + break; + case 5: + draft.shift(); + break; + case 6: + draft.unshift(item); + break; + case 7: + draft.splice(a, b); + break; + case 8: + draft.splice(a, b, item); + break; + case 9: + draft.reverse(); + break; + case 10: + draft.sort(); + break; + case 11: + draft.fill(item, a, b); + break; + case 12: + draft.copyWithin(a, b); + break; + case 13: + if (draft[a] && typeof draft[a] === 'object') draft[a].value++; + break; + } + } + }; + // Native methods provide the oracle, with Mutative's documented delete + // semantics: present indices become undefined, missing ones stay absent. + const expected = structuredClone(base); + recipe( + new Proxy(expected, { + deleteProperty(target, key) { + if (Object.hasOwn(target, key)) (target as any)[key] = undefined; + return true; + }, + }) + ); + const [state, patches, inverse] = create(base, recipe, { + enablePatches: modes[sample % modes.length], + enableAutoFreeze: sample % 3 === 0, + }); + const context = `sample ${sample}: ${JSON.stringify(operations)}`; + expect(state, context).toStrictEqual(expected); + expect(base, context).toStrictEqual(before); + expect(create(structuredClone(before), recipe), context).toStrictEqual( + state + ); + const replay = apply(base, patches); + expect(replay, context).toStrictEqual(state); + expect(apply(state, inverse), context).toStrictEqual(before); + expect(apply(replay, inverse), context).toStrictEqual(before); + expect(apply(apply(replay, inverse), patches), context).toStrictEqual( + state + ); + } +}); diff --git a/website/content/docs/advanced-guides/patches.mdx b/website/content/docs/advanced-guides/patches.mdx index b572ceb6..c681aa4a 100644 --- a/website/content/docs/advanced-guides/patches.mdx +++ b/website/content/docs/advanced-guides/patches.mdx @@ -46,18 +46,18 @@ expect(apply(state, inversePatches)).toEqual(baseState); - **Operations and paths.** Patches use `add`, `remove` and `replace`. A path leads from the root to the changed value through object keys, array indices, Map keys as they are, objects and arrays included, and the positions of Set items. A recipe that returns a new state gets one `replace` patch with an empty path. - **Order.** The patches of a nested draft come before those of its parents, as in Immer. - **Values.** A patch value is the object that the next state holds, frozen with it when `enableAutoFreeze` is on, so copy a patch value before changing it. `apply()` copies patch values before applying them. -- **Arrays.** `shift()`, `unshift()`, `splice()`, `reverse()` and `sort()` emit a `replace` patch for each index whose element changed, and an `add` patch for each index past the old length. An array that gets shorter gets one `replace` patch of its `length` by default, or a `remove` patch for each index it loses with `arrayLengthAssignment: false`. An array that a recipe shortens and lengthens again also gets patches for the indices that the longer length exposes again. +- **Arrays.** `shift()`, `unshift()`, `splice()`, `reverse()` and `sort()` emit a `replace` patch for each index whose element changed, and an `add` patch for each index past the old length. An array that gets shorter gets one `replace` patch of its `length` by default, or a `remove` patch for each index it loses with `arrayLengthAssignment: false`. When holes change, patches rebuild the affected suffix to preserve them in both directions; see [Sparse arrays](#sparse-arrays). - **Maps.** `set()` emits an `add` patch for a new key and a `replace` patch for an existing one, and `delete()` a `remove` patch. - **Sets.** Patches add an item by its value and remove one by the value it holds; see [Sets of objects](#sets-of-objects). - **Moved drafts.** A changed draft that leaves its key, because `sort()` or an assignment moved it or another value replaced it there, emits no patches under its old path; the patches of its parent carry its value. - **Applying patches.** `apply()` applies `add`, `remove` and `replace` patches and accepts `-` as the index that appends to an array. It throws for other operations and for paths through `__proto__` or `constructor`. It takes the `enableAutoFreeze`, `strict` and `mark` options, or `mutable: true` to change the state in place, which throws for a patch that replaces the root state with another value, and it changes a draft in place. -- **JSON Patch.** With `pathAsArray: false` and `arrayLengthAssignment: false`, the patches of objects and arrays are JSON Patch operations. Maps and Sets have no JSON Patch counterpart. +- **JSON Patch.** With `pathAsArray: false` and `arrayLengthAssignment: false`, patches of JSON-compatible objects and arrays are JSON Patch operations. Maps, Sets and array holes have no JSON counterpart. [Comparison with Immer](/docs/extra-topics/comparison-with-immer#patches) lists where these patches differ from Immer's. ## JSON patches -`enablePatches` takes `true`, or an object with two options that set the shape of the patches. With both set to `false`, the patches of objects and arrays are [JSON Patch](https://datatracker.ietf.org/doc/html/rfc6902) operations, which other JSON Patch libraries can apply ([related discussion](https://github.com/unadlib/mutative/issues/6)). +`enablePatches` takes `true`, or an object with two options that set the shape of the patches. With both set to `false`, patches of JSON-compatible objects and arrays are [JSON Patch](https://datatracker.ietf.org/doc/html/rfc6902) operations, which other JSON Patch libraries can apply ([related discussion](https://github.com/unadlib/mutative/issues/6)). ### pathAsArray - default: true @@ -125,6 +125,27 @@ expect(inversePatches).toEqual([ A `remove` patch per index takes more time and more patches for large arrays than one `replace` patch of the `length`, so leave `arrayLengthAssignment` on unless the patches must be JSON Patch operations. +## Sparse arrays + +A hole is an absent index, which differs from an own index whose value is `undefined`: array methods such as `map()` and `forEach()` skip holes. Patches and inverse patches preserve this distinction, including when a recipe lengthens an array, fills a hole with `undefined`, or moves holes with an array method. + +```ts +const base = new Array(2); +base[0] = 1; + +const [state, patches, inverse] = create(base, (draft) => { + draft.unshift(0); +}, { enablePatches: true }); + +expect(2 in state).toBe(false); +expect(2 in apply(base, patches)).toBe(false); +expect(1 in apply(state, inverse)).toBe(false); +``` + +An index patch carries a value, so it cannot represent a hole. When an update changes holes, patches truncate the affected suffix, grow `length` to leave holes, and restore its own indices. This can produce more patches than the number of changed values, while preserving the array itself for mutable application and application on a draft, also inside a Set. + +With `arrayLengthAssignment: false`, truncation still uses per-index `remove` patches, but recreating holes needs a `replace` patch of `length`. Apply these patches with Mutative's `apply()`: sparse arrays are JavaScript data, not JSON data, so their patches are not portable JSON Patch operations. JSON serialization turns array holes into `null` and cannot preserve their structure. + ## Undo and redo The inverse patches of each change undo it, and its patches redo it: From 0b74b476b5f36f87db66c12e21dfe722e637e61b Mon Sep 17 00:00:00 2001 From: unadlib Date: Tue, 27 Oct 2026 01:46:41 +0800 Subject: [PATCH 05/13] build: refresh size budgets for sparse array patches --- package.json | 6 +-- scripts/build-size-baseline.json | 84 ++++++++++++++++---------------- 2 files changed, 45 insertions(+), 45 deletions(-) diff --git a/package.json b/package.json index be1f9c09..ced3ac96 100644 --- a/package.json +++ b/package.json @@ -62,19 +62,19 @@ "name": "production CJS, all exports", "path": "dist/mutative.cjs.production.min.js", "import": "*", - "limit": "8.7 KB" + "limit": "9.0 KB" }, { "name": "ESM, create", "path": "dist/mutative.esm.mjs", "import": "{ create }", - "limit": "7.7 KB" + "limit": "7.9 KB" }, { "name": "ESM, all exports", "path": "dist/mutative.esm.mjs", "import": "*", - "limit": "8.6 KB" + "limit": "8.9 KB" } ], "repository": { diff --git a/scripts/build-size-baseline.json b/scripts/build-size-baseline.json index 96aeb20e..014459e8 100644 --- a/scripts/build-size-baseline.json +++ b/scripts/build-size-baseline.json @@ -1,8 +1,8 @@ { "reference": { - "revision": "4f58b62296df553e411bb756ea0263d8d65fc21f", - "description": "Deleting an index that an array draft does not have changes nothing", - "node": "v24.22.0", + "revision": "d28e9bd53ef88bbf600cade5a6792bc1f78ba993", + "description": "Preserve sparse array holes in forward and inverse patches", + "node": "v24.16.0", "commands": [ "pnpm install --frozen-lockfile", "pnpm build" @@ -15,69 +15,69 @@ "esbuild": "0.24.0", "measurements": { "artifact/mutative.cjs.production.min.js": { - "raw": 27470, - "gzip": 9242, - "brotli": 8489 + "raw": 28117, + "gzip": 9452, + "brotli": 8663 }, "artifact/mutative.umd.production.min.js": { - "raw": 27625, - "gzip": 9307, - "brotli": 8532 + "raw": 28272, + "gzip": 9524, + "brotli": 8713 }, "artifact/mutative.esm.production.min.mjs": { - "raw": 27442, - "gzip": 9266, - "brotli": 8508 + "raw": 28089, + "gzip": 9478, + "brotli": 8685 }, "artifact/mutative.cjs.development.js": { - "raw": 73224, - "gzip": 17836, - "brotli": 15475 + "raw": 74888, + "gzip": 18165, + "brotli": 15739 }, "artifact/mutative.umd.development.js": { - "raw": 75511, - "gzip": 18038, - "brotli": 15647 + "raw": 77214, + "gzip": 18365, + "brotli": 15910 }, "artifact/mutative.esm.js": { - "raw": 74059, - "gzip": 17927, - "brotli": 15549 + "raw": 75723, + "gzip": 18254, + "brotli": 15796 }, "artifact/mutative.esm.mjs": { - "raw": 74060, - "gzip": 17929, - "brotli": 15549 + "raw": 75724, + "gzip": 18256, + "brotli": 15794 }, "consumer/import/create": { - "raw": 24620, - "gzip": 8628, - "brotli": 7936 + "raw": 25280, + "gzip": 8859, + "brotli": 8141 }, "consumer/import/patches": { - "raw": 26683, - "gzip": 9329, - "brotli": 8557 + "raw": 27343, + "gzip": 9545, + "brotli": 8746 }, "consumer/import/all": { - "raw": 27468, - "gzip": 9588, - "brotli": 8793 + "raw": 28129, + "gzip": 9804, + "brotli": 8994 }, "consumer/require/create": { - "raw": 26968, - "gzip": 9564, - "brotli": 8762 + "raw": 27598, + "gzip": 9780, + "brotli": 8954 }, "consumer/require/patches": { - "raw": 27036, - "gzip": 9602, - "brotli": 8801 + "raw": 27666, + "gzip": 9818, + "brotli": 9021 }, "consumer/require/all": { - "raw": 26933, - "gzip": 9543, - "brotli": 8768 + "raw": 27563, + "gzip": 9759, + "brotli": 8984 } } } From 19e6bdac8e75848acb7803b11cf55e847d402500 Mon Sep 17 00:00:00 2001 From: unadlib Date: Mon, 26 Oct 2026 12:15:16 -0700 Subject: [PATCH 06/13] fix: restore only the suffix of a sparse array, and only its indices --- src/patch.ts | 101 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 78 insertions(+), 23 deletions(-) diff --git a/src/patch.ts b/src/patch.ts index 7b9aee2a..239690b6 100644 --- a/src/patch.ts +++ b/src/patch.ts @@ -23,14 +23,70 @@ function cloneIfNeeded(target: T): T { const hasOwn = Object.prototype.hasOwnProperty; +// In Node.js 24, checking an index takes about 7 ns, or 30 ns in a +// dictionary-mode array, and enumerating an own key about 150 ns. A suffix is +// checked index by index until this many holes have passed, and the rest of a +// long gap is crossed by enumerating own keys. +const SPARSE_HOLE_LIMIT = 65536; + +// Patches that restore the own indices of `to` from `start` on, including +// non-enumerable ones. `indices`, if given, holds all of them, among others, +// in ascending order. +function restoreSuffix( + to: any[], + start: number, + indices: number[] | null, + basePath: any[], + result: Patches, + pathAsArray: boolean +) { + const restore = (index: number) => + result.push({ + op: Operation.Replace, + path: escapePath(basePath.concat([index]), pathAsArray), + value: cloneIfNeeded(to[index]), + }); + if (indices !== null) { + for (let position = 0; position < indices.length; position += 1) { + const index = indices[position]; + if (index >= start && index < to.length && hasOwn.call(to, index)) { + restore(index); + } + } + return; + } + let index = start; + let holes = 0; + while (index < to.length && holes <= SPARSE_HOLE_LIMIT) { + if (hasOwn.call(to, index)) restore(index); + else holes += 1; + index += 1; + } + if (index === to.length) return; + // Array indices only, not length or custom properties such as '1.5'. + for (const key of Object.getOwnPropertyNames(to)) { + const own = Number(key); + if ( + Number.isInteger(own) && + own >= index && + own < to.length && + String(own) === key + ) { + restore(own); + } + } +} + // Index patches carry values, so neither an undefined value nor an index // removal can represent a hole. Rebuild the affected suffix in each direction: // truncate it, grow the length to leave holes, then restore only own indices. // Keeping the array itself supports mutable application and arrays inside Sets. +// `added`, when known, holds every own index that the copy has from `start` on. function generateSparseArrayPatches( original: any[], copy: any[], start: number, + added: number[] | null, basePath: any[], patches: Patches, inversePatches: Patches, @@ -38,7 +94,12 @@ function generateSparseArrayPatches( arrayLengthAssignment: boolean ) { const lengthPath = escapePath(basePath.concat(['length']), pathAsArray); - const rebuild = (from: any[], to: any[], result: Patches) => { + const rebuild = ( + from: any[], + to: any[], + result: Patches, + indices: number[] | null + ) => { const cut = Math.min(start, to.length); if (arrayLengthAssignment) { if (from.length > cut) { @@ -52,30 +113,18 @@ function generateSparseArrayPatches( }); } } + if (to.length <= cut) return; // JSON cannot encode holes. Growing a sparse array needs a length patch // even when shrinking arrays use per-index removals. - if (to.length > cut) { - result.push({ - op: Operation.Replace, - path: lengthPath, - value: to.length, - }); - } - // Enumerate own indices instead of walking potentially huge gaps. Include - // non-enumerable indices too, but not length or custom array properties. - for (const key of Object.getOwnPropertyNames(to)) { - const index = Number(key); - if (index >= start && index < to.length && String(index) === key) { - result.push({ - op: Operation.Replace, - path: escapePath(basePath.concat([index]), pathAsArray), - value: cloneIfNeeded(to[index]), - }); - } - } + result.push({ + op: Operation.Replace, + path: lengthPath, + value: to.length, + }); + restoreSuffix(to, cut, indices, basePath, result, pathAsArray); }; - rebuild(original, copy, patches); - rebuild(copy, original, inversePatches); + rebuild(original, copy, patches, added); + rebuild(copy, original, inversePatches, null); } function generateArrayPatches( @@ -88,7 +137,8 @@ function generateArrayPatches( let { original, assignedMap, options } = proxyState; let copy = proxyState.copy!; const { arrayLengthAssignment = true } = options.enablePatches; - if (copy.length < original.length) { + const shorter = copy.length < original.length; + if (shorter) { [original, copy] = [copy, original]; [patches, inversePatches] = [inversePatches, patches]; } @@ -132,6 +182,7 @@ function generateArrayPatches( original, copy, index, + null, basePath, patches, inversePatches, @@ -159,10 +210,14 @@ function generateArrayPatches( for (let index = original.length; index < copy.length; index += 1) { const value = copy[index]; if (value === undefined && !hasOwn.call(copy, index)) { + // Every index that the copy has past the end of the original was set + // by the recipe, so `indices` holds it. A shorter copy was swapped, + // which makes `copy` the original array. return generateSparseArrayPatches( original, copy, index, + shorter ? null : indices, basePath, patches, inversePatches, From 4c2d59609dd0601e1353439ce06ca64a673ffe8b Mon Sep 17 00:00:00 2001 From: unadlib Date: Mon, 26 Oct 2026 12:19:21 -0700 Subject: [PATCH 07/13] fix: rebuild a sparse array only in the direction that makes a hole --- src/patch.ts | 210 ++++++++++-------- .../content/docs/advanced-guides/patches.mdx | 4 +- 2 files changed, 114 insertions(+), 100 deletions(-) diff --git a/src/patch.ts b/src/patch.ts index 239690b6..9148696d 100644 --- a/src/patch.ts +++ b/src/patch.ts @@ -78,53 +78,45 @@ function restoreSuffix( } // Index patches carry values, so neither an undefined value nor an index -// removal can represent a hole. Rebuild the affected suffix in each direction: -// truncate it, grow the length to leave holes, then restore only own indices. -// Keeping the array itself supports mutable application and arrays inside Sets. -// `added`, when known, holds every own index that the copy has from `start` on. -function generateSparseArrayPatches( - original: any[], - copy: any[], +// removal can represent a hole. Patches that turn an own index of `from` into +// a hole of `to` rebuild the suffix from there: they truncate it, grow the +// length to leave holes, then restore only own indices. Filling a hole takes +// an index patch, so only that direction rebuilds. Keeping the array itself +// supports mutable application and arrays inside Sets. `indices`, when known, +// holds every own index that `to` has from `start` on. +function rebuildSuffix( + from: any[], + to: any[], start: number, - added: number[] | null, + indices: number[] | null, basePath: any[], - patches: Patches, - inversePatches: Patches, + result: Patches, pathAsArray: boolean, arrayLengthAssignment: boolean ) { const lengthPath = escapePath(basePath.concat(['length']), pathAsArray); - const rebuild = ( - from: any[], - to: any[], - result: Patches, - indices: number[] | null - ) => { - const cut = Math.min(start, to.length); - if (arrayLengthAssignment) { - if (from.length > cut) { - result.push({ op: Operation.Replace, path: lengthPath, value: cut }); - } - } else { - for (let index = from.length - 1; index >= cut; index -= 1) { - result.push({ - op: Operation.Remove, - path: escapePath(basePath.concat([index]), pathAsArray), - }); - } + const cut = Math.min(start, to.length); + if (arrayLengthAssignment) { + if (from.length > cut) { + result.push({ op: Operation.Replace, path: lengthPath, value: cut }); } - if (to.length <= cut) return; - // JSON cannot encode holes. Growing a sparse array needs a length patch - // even when shrinking arrays use per-index removals. - result.push({ - op: Operation.Replace, - path: lengthPath, - value: to.length, - }); - restoreSuffix(to, cut, indices, basePath, result, pathAsArray); - }; - rebuild(original, copy, patches, added); - rebuild(copy, original, inversePatches, null); + } else { + for (let index = from.length - 1; index >= cut; index -= 1) { + result.push({ + op: Operation.Remove, + path: escapePath(basePath.concat([index]), pathAsArray), + }); + } + } + if (to.length <= cut) return; + // JSON cannot encode holes. Growing a sparse array needs a length patch + // even when shrinking arrays use per-index removals. + result.push({ + op: Operation.Replace, + path: lengthPath, + value: to.length, + }); + restoreSuffix(to, cut, indices, basePath, result, pathAsArray); } function generateArrayPatches( @@ -169,72 +161,94 @@ function generateArrayPatches( for (let index = diffStart; index < diffEnd; index += 1) indices.push(index); for (; position < assigned.length; position += 1) indices.push(assigned[position]); + // The first index at which each direction turns an own index into a hole. + let forward = -1; + let inverse = -1; for (let position = 0; position < indices.length; position += 1) { const index = indices[position]; - if (index < original.length) { - const value = copy[index]; - const previous = original[index]; - if ( - (value === undefined || previous === undefined) && - hasOwn.call(copy, index) !== hasOwn.call(original, index) - ) { - return generateSparseArrayPatches( - original, - copy, - index, - null, - basePath, - patches, - inversePatches, - pathAsArray, - arrayLengthAssignment - ); + if (index >= original.length) break; + const value = copy[index]; + const previous = original[index]; + // A hole reads as `undefined`. + let inCopy = true; + let inOriginal = true; + if (value === undefined || previous === undefined) { + inCopy = hasOwn.call(copy, index); + inOriginal = hasOwn.call(original, index); + } + // As the set trap compares, so 0 and -0 differ and NaN equals itself. + if (inCopy !== inOriginal || !isEqual(value, previous)) { + const _path = basePath.concat([index]); + const path = escapePath(_path, pathAsArray); + if (forward === -1) { + if (inCopy) { + patches.push({ + op: Operation.Replace, + path, + value: cloneIfNeeded(value), + }); + } else { + forward = index; + } } - // As the set trap compares, so 0 and -0 differ and NaN equals itself. - if (!isEqual(value, previous)) { - const _path = basePath.concat([index]); - const path = escapePath(_path, pathAsArray); - patches.push({ - op: Operation.Replace, - path, - value: cloneIfNeeded(value), - }); - inversePatches.push({ - op: Operation.Replace, - path, - value: cloneIfNeeded(previous), - }); + if (inverse === -1) { + if (inOriginal) { + inversePatches.push({ + op: Operation.Replace, + path, + value: cloneIfNeeded(previous), + }); + } else { + inverse = index; + } } + if (forward !== -1 && inverse !== -1) break; } } - for (let index = original.length; index < copy.length; index += 1) { - const value = copy[index]; - if (value === undefined && !hasOwn.call(copy, index)) { - // Every index that the copy has past the end of the original was set - // by the recipe, so `indices` holds it. A shorter copy was swapped, - // which makes `copy` the original array. - return generateSparseArrayPatches( - original, - copy, - index, - shorter ? null : indices, - basePath, - patches, - inversePatches, - pathAsArray, - arrayLengthAssignment - ); + if (forward === -1) { + for (let index = original.length; index < copy.length; index += 1) { + const value = copy[index]; + if (value === undefined && !hasOwn.call(copy, index)) { + forward = index; + break; + } + const _path = basePath.concat([index]); + const path = escapePath(_path, pathAsArray); + patches.push({ + op: Operation.Add, + path, + // If it is a draft, it needs to be deep cloned, and it may also be non-draft. + value: cloneIfNeeded(value), + }); } - const _path = basePath.concat([index]); - const path = escapePath(_path, pathAsArray); - patches.push({ - op: Operation.Add, - path, - // If it is a draft, it needs to be deep cloned, and it may also be non-draft. - value: cloneIfNeeded(value), - }); } - if (original.length < copy.length) { + if (forward !== -1) { + // Every index that the copy has past the end of the original was set by + // the recipe, so `indices` holds it. A shorter copy was swapped, which + // makes `copy` the original array. + rebuildSuffix( + original, + copy, + forward, + shorter || forward < original.length ? null : indices, + basePath, + patches, + pathAsArray, + arrayLengthAssignment + ); + } + if (inverse !== -1) { + rebuildSuffix( + copy, + original, + inverse, + null, + basePath, + inversePatches, + pathAsArray, + arrayLengthAssignment + ); + } else if (original.length < copy.length) { // https://www.rfc-editor.org/rfc/rfc6902#appendix-A.4 // For performance, here we only generate an operation that replaces the length of the array, // which is inconsistent with JSON Patch specification diff --git a/website/content/docs/advanced-guides/patches.mdx b/website/content/docs/advanced-guides/patches.mdx index c681aa4a..ea6f2f40 100644 --- a/website/content/docs/advanced-guides/patches.mdx +++ b/website/content/docs/advanced-guides/patches.mdx @@ -46,7 +46,7 @@ expect(apply(state, inversePatches)).toEqual(baseState); - **Operations and paths.** Patches use `add`, `remove` and `replace`. A path leads from the root to the changed value through object keys, array indices, Map keys as they are, objects and arrays included, and the positions of Set items. A recipe that returns a new state gets one `replace` patch with an empty path. - **Order.** The patches of a nested draft come before those of its parents, as in Immer. - **Values.** A patch value is the object that the next state holds, frozen with it when `enableAutoFreeze` is on, so copy a patch value before changing it. `apply()` copies patch values before applying them. -- **Arrays.** `shift()`, `unshift()`, `splice()`, `reverse()` and `sort()` emit a `replace` patch for each index whose element changed, and an `add` patch for each index past the old length. An array that gets shorter gets one `replace` patch of its `length` by default, or a `remove` patch for each index it loses with `arrayLengthAssignment: false`. When holes change, patches rebuild the affected suffix to preserve them in both directions; see [Sparse arrays](#sparse-arrays). +- **Arrays.** `shift()`, `unshift()`, `splice()`, `reverse()` and `sort()` emit a `replace` patch for each index whose element changed, and an `add` patch for each index past the old length. An array that gets shorter gets one `replace` patch of its `length` by default, or a `remove` patch for each index it loses with `arrayLengthAssignment: false`. Patches preserve holes in both directions: filling a hole takes a `replace` patch, and recreating one rebuilds the array from its index; see [Sparse arrays](#sparse-arrays). - **Maps.** `set()` emits an `add` patch for a new key and a `replace` patch for an existing one, and `delete()` a `remove` patch. - **Sets.** Patches add an item by its value and remove one by the value it holds; see [Sets of objects](#sets-of-objects). - **Moved drafts.** A changed draft that leaves its key, because `sort()` or an assignment moved it or another value replaced it there, emits no patches under its old path; the patches of its parent carry its value. @@ -142,7 +142,7 @@ expect(2 in apply(base, patches)).toBe(false); expect(1 in apply(state, inverse)).toBe(false); ``` -An index patch carries a value, so it cannot represent a hole. When an update changes holes, patches truncate the affected suffix, grow `length` to leave holes, and restore its own indices. This can produce more patches than the number of changed values, while preserving the array itself for mutable application and application on a draft, also inside a Set. +An index patch carries a value, so it cannot represent a hole. Filling a hole takes a `replace` patch, but the patches that recreate a hole shorten the array to its index, lengthen it again to leave holes, and restore the elements after it, so their number grows with those elements: filling a hole before 10,000 elements yields one patch and 10,002 inverse patches. A recipe that makes a hole before the last element gets such patches, and inverse patches that fill it. Holes that an array gets past its old length need only a `replace` patch of its `length`. These patches preserve the array itself for mutable application and application on a draft, also inside a Set. With `arrayLengthAssignment: false`, truncation still uses per-index `remove` patches, but recreating holes needs a `replace` patch of `length`. Apply these patches with Mutative's `apply()`: sparse arrays are JavaScript data, not JSON data, so their patches are not portable JSON Patch operations. JSON serialization turns array holes into `null` and cannot preserve their structure. From b0ec0a05ad2c746f7ba7e67b1ce9aaa9f3d7082a Mon Sep 17 00:00:00 2001 From: unadlib Date: Mon, 26 Oct 2026 12:20:48 -0700 Subject: [PATCH 08/13] build: refresh size budgets for rebuilding sparse array suffixes --- package.json | 6 +-- scripts/build-size-baseline.json | 84 ++++++++++++++++---------------- 2 files changed, 45 insertions(+), 45 deletions(-) diff --git a/package.json b/package.json index ced3ac96..46956f4b 100644 --- a/package.json +++ b/package.json @@ -62,19 +62,19 @@ "name": "production CJS, all exports", "path": "dist/mutative.cjs.production.min.js", "import": "*", - "limit": "9.0 KB" + "limit": "9.1 KB" }, { "name": "ESM, create", "path": "dist/mutative.esm.mjs", "import": "{ create }", - "limit": "7.9 KB" + "limit": "8.1 KB" }, { "name": "ESM, all exports", "path": "dist/mutative.esm.mjs", "import": "*", - "limit": "8.9 KB" + "limit": "9.0 KB" } ], "repository": { diff --git a/scripts/build-size-baseline.json b/scripts/build-size-baseline.json index 014459e8..8c26af34 100644 --- a/scripts/build-size-baseline.json +++ b/scripts/build-size-baseline.json @@ -1,8 +1,8 @@ { "reference": { - "revision": "d28e9bd53ef88bbf600cade5a6792bc1f78ba993", - "description": "Preserve sparse array holes in forward and inverse patches", - "node": "v24.16.0", + "revision": "eba635a9289a9ddf9a65221059cd9f51d97d8c42", + "description": "Rebuild a sparse array only in the direction that makes a hole, and restore only its suffix", + "node": "v24.22.0", "commands": [ "pnpm install --frozen-lockfile", "pnpm build" @@ -15,69 +15,69 @@ "esbuild": "0.24.0", "measurements": { "artifact/mutative.cjs.production.min.js": { - "raw": 28117, - "gzip": 9452, - "brotli": 8663 + "raw": 28489, + "gzip": 9621, + "brotli": 8816 }, "artifact/mutative.umd.production.min.js": { - "raw": 28272, - "gzip": 9524, - "brotli": 8713 + "raw": 28644, + "gzip": 9696, + "brotli": 8863 }, "artifact/mutative.esm.production.min.mjs": { - "raw": 28089, - "gzip": 9478, - "brotli": 8685 + "raw": 28461, + "gzip": 9644, + "brotli": 8838 }, "artifact/mutative.cjs.development.js": { - "raw": 74888, - "gzip": 18165, - "brotli": 15739 + "raw": 75852, + "gzip": 18457, + "brotli": 15984 }, "artifact/mutative.umd.development.js": { - "raw": 77214, - "gzip": 18365, - "brotli": 15910 + "raw": 78214, + "gzip": 18668, + "brotli": 16166 }, "artifact/mutative.esm.js": { - "raw": 75723, - "gzip": 18254, - "brotli": 15796 + "raw": 76687, + "gzip": 18552, + "brotli": 16050 }, "artifact/mutative.esm.mjs": { - "raw": 75724, - "gzip": 18256, - "brotli": 15794 + "raw": 76688, + "gzip": 18554, + "brotli": 16052 }, "consumer/import/create": { - "raw": 25280, - "gzip": 8859, - "brotli": 8141 + "raw": 25665, + "gzip": 9037, + "brotli": 8337 }, "consumer/import/patches": { - "raw": 27343, - "gzip": 9545, - "brotli": 8746 + "raw": 27729, + "gzip": 9725, + "brotli": 8927 }, "consumer/import/all": { - "raw": 28129, - "gzip": 9804, - "brotli": 8994 + "raw": 28515, + "gzip": 9985, + "brotli": 9170 }, "consumer/require/create": { - "raw": 27598, - "gzip": 9780, - "brotli": 8954 + "raw": 27977, + "gzip": 9994, + "brotli": 9182 }, "consumer/require/patches": { - "raw": 27666, - "gzip": 9818, - "brotli": 9021 + "raw": 28045, + "gzip": 10029, + "brotli": 9211 }, "consumer/require/all": { - "raw": 27563, - "gzip": 9759, - "brotli": 8984 + "raw": 27942, + "gzip": 9973, + "brotli": 9165 } } } From f8f9ec8d9b6da8be7530863cc62b39a60e259409 Mon Sep 17 00:00:00 2001 From: unadlib Date: Mon, 26 Oct 2026 12:27:27 -0700 Subject: [PATCH 09/13] test: cover numeric custom keys and sparse array patch workloads --- README.md | 2 +- perf-testing/README.md | 8 ++- perf-testing/additional-workloads.mjs | 36 +++++++++++++ perf-testing/graph.mjs | 7 ++- perf-testing/graph.test.mjs | 14 ++++++ perf-testing/scenarios.mjs | 13 +++-- perf-testing/scenarios.test.mjs | 17 +++++++ test/sparse-array-patches.test.ts | 50 +++++++++++++++++++ .../docs/getting-started/performance.mdx | 2 +- 9 files changed, 140 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 214a0c17..85ff7232 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Mutative 2.0.0 was 3.6x faster than Immer 11.1.18 with matched settings and 6.6x
Selected results -The [benchmark suite](./perf-testing/README.md) times 99 workloads: Immer's own performance tests, array methods, reads, Map and Set values, object records, class instances, a deep path, patch application, returned values, and searches. Its last full run measured 97 of them, and a focused run the two that return fresh data. It compares Mutative with Immer 11.1.18 and with reducers written by hand, after checking every result against those reducers. With matched settings, both libraries freeze or both do not, and both generate patches or both do not. With each library's defaults, Mutative without auto-freeze and Immer with it, Mutative was faster in 154 of 157 cases. The other 3 return a state that Immer froze earlier: Immer skips frozen values when it searches a returned state for drafts, while Mutative, which does not freeze by default, searches it unless the recipe wraps it in [`rawReturn()`](https://mutative.js.org/docs/api-reference/rawreturn#performance-compared-with-immer), which took 0.26 µs. +The [benchmark suite](./perf-testing/README.md) times 101 workloads: Immer's own performance tests, array methods, sparse arrays, reads, Map and Set values, object records, class instances, a deep path, patch application, returned values, and searches. Its last full run measured 97 of them, and a focused run the two that return fresh data; the two sparse-array workloads came later. It compares Mutative with Immer 11.1.18 and with reducers written by hand, after checking every result against those reducers. With matched settings, both libraries freeze or both do not, and both generate patches or both do not. With each library's defaults, Mutative without auto-freeze and Immer with it, Mutative was faster in 154 of 157 cases. The other 3 return a state that Immer froze earlier: Immer skips frozen values when it searches a returned state for drafts, while Mutative, which does not freeze by default, searches it unless the recipe wraps it in [`rawReturn()`](https://mutative.js.org/docs/api-reference/rawreturn#performance-compared-with-immer), which took 0.26 µs. Times are microseconds per update, medians of three runs on an Apple M1 Max with Node.js 24.16.0, each library in a process of its own; lower is better. Mutative, the first Immer column, and the hand-written reducers run without auto-freeze; the second Immer column shows Immer's default. diff --git a/perf-testing/README.md b/perf-testing/README.md index d1348d6d..bf8492cc 100644 --- a/perf-testing/README.md +++ b/perf-testing/README.md @@ -1,6 +1,6 @@ # Mutative benchmarks -This suite ports the workloads of Immer's [`perf-testing` directory](https://github.com/immerjs/immer/tree/061c2425e1c9dff89e4e4189d42af1b7839dfe0a/perf-testing) and extends them with Map and Set values, object records, class instances, a deep path, a combined large-state update, patch application, producers that return a value, and searches of changed arrays. The upstream MIT license is retained in [LICENSE](./LICENSE). It is the repository's only benchmark suite. +This suite ports the workloads of Immer's [`perf-testing` directory](https://github.com/immerjs/immer/tree/061c2425e1c9dff89e4e4189d42af1b7839dfe0a/perf-testing) and extends them with Map and Set values, object records, class instances, a deep path, a combined large-state update, patch application, producers that return a value, searches of changed arrays, and sparse arrays. The upstream MIT license is retained in [LICENSE](./LICENSE). It is the repository's only benchmark suite. It compares a **candidate production Mutative build**, the **exactly pinned Mutative v1.3.0 npm baseline** (`mutative-v1` alias), **Immer 11.1.18** in the root `package.json` and `pnpm-lock.yaml`, and a **hand-written reducer**: the spread-and-copy implementation that is also every scenario's reference result. Immer 11.1.18 was npm's `latest` on 2026-09-30. The candidate defaults to the current checkout. Its actual version, source revision, and production hash are reported. Immer's `enableArrayMethods` plugin is enabled only when a run passes `--immer-array-methods`; such reports record `arrayMethodsEnabled: true` and the budget gate rejects them. Mutative's native array methods need no option. Immer's `enableMapSet` plugin is loaded only in processes that run Map or Set scenarios; see [fairness and interpretation](#fairness-and-interpretation). See the existing [array-method reproductions](../test/immer-array-methods.md). @@ -89,6 +89,7 @@ Each generated report includes both scenarios with matched freeze modes. For the | Small state | small-object-update, small-array-1-update, small-array-10-update | 1 | | Common array operations | 11 operations × primitive, shallow-object, and nested-object elements | 1 | | Moved elements | shift-and-update | 1 | +| Sparse arrays | sparse-append-gap, sparse-fill-slots | 1 and 10 | | Mutation density | mutation-density-1pct, mutation-density-10pct, mutation-density-100pct | 1 | | Map and Set values | map-update, map-update-10pct, map-insert, map-delete, map-read, map-forEach, set-add, set-delete, set-read, set-update, set-update-10pct | 1 | | Producers beside unchanged collections | map-set-beside | 10 | @@ -108,6 +109,8 @@ Additional `array-{operation}-{shape}` cases cover push, pop, shift, unshift, mi `shift-and-update` removes the first row of an array of nested rows with `shift()`, which moves every other row, and then updates the nested value of the middle row. A draft of a moved row needs the row's index in the original array, which differs from its new index. +`sparse-append-gap` assigns a row one index past the end of an array of shallow rows, which leaves a hole before it. `sparse-fill-slots` fills the first slots of a preallocated array of `--array-size` holes, one producer call per slot, as many as the state reuse scenarios make, ten by default. The inverse patches of filling a slot recreate its hole: in Mutative's removal format, they remove each slot after it and lengthen the array again. + `update` uses `find` at index 0; `update-high` searches around 80% of the array. `remove` uses `splice(0, 1)`; `remove-high` searches by ID before splicing. The wide-object scenarios **insert properties**, rather than edit existing ones. `concat` retains upstream's prepend-500-then-truncate behavior: at array size 100 it replaces all rows. `filter` retains 50% of the rows; upstream's single `filter(0)` produced an empty array and its unused percentage calculation was removed. Fixtures are deterministic instead of using `Math.random()`. Map and Set scenarios use a `Map` of `--array-size` rows keyed by number, a `Map` of as many numbers, a `Set` of as many numbers, or a `Set` of as many objects. They update the nested value of the middle row or of the first 10% of rows, insert a key, delete the middle key, sum every nested value through `values()`, or sum the numbers with `forEach()`; or they add a number, delete the middle number, look up the middle number and a missing one and read the size without changing the Set, or update the first object or the first 10% of objects through the Set's iterator. `map-set-beside` runs as many producers as the state reuse scenarios, ten by default, on the evolving state: the first inserts a row into such a `Map` and adds a number to such a `Set`, which copies both, and the others increment a number beside them. With auto-freeze, the input is pre-frozen like any other, but the copies are new: the first producer freezes them, and the others find them frozen. Mutative 1.3.0 only replaced the mutators of the `Map` and `Set` instances it froze, so each of its producers walked both copies again. @@ -126,6 +129,7 @@ The `search-*` scenarios find the last row of an array of nested rows and update - Both libraries run production artifacts with the selected patch mode. Each gets the same recipe, action values, and fixture structure. - With patches enabled, Mutative uses `enablePatches: { arrayLengthAssignment: false }`. Immer uses `produceWithPatches` after one-time `enablePatches` setup. Both return forward and inverse patches using array paths and index removals. This intentionally disables Mutative's default array-length patch shortcut to match Immer's removal format. Immer's array-method plugin is off unless `--immer-array-methods` is passed. +- The patches of Immer and Mutative v1 put `undefined` where holes were, so they do not replay the states of the `sparse-*` scenarios. With patches enabled, only the candidate runs those scenarios, and reports have no Immer ratio for them. - Patch generation is timed at **every reducer call**, including all calls in reuse, mixed, and RTKQ scenarios. Each `[state, patches, inversePatches]` tuple escapes via `do_not_optimize`; tuples are not accumulated. Replay, JSON serialization, and patch-consuming application work are outside timing, except in the `apply-*` scenarios, which time patch application alone. Reports include forward/inverse operation counts per full scenario. - The hand-written reducer is the reference implementation of every scenario: spreads, `slice`, `map`, and new `Map` and `Set` copies, with plain loops for the values that recipes read through drafts. It runs with freeze and patches off only, since it neither freezes nor produces patches. It is an ordinary reducer, not the fastest possible code. - Immer needs `enableMapSet()` for Map and Set values. Once loaded, Immer calls the plugin while finalizing every draft: `small-object-update` measured about 4% slower with it (0.67 µs instead of 0.64 µs), 100-row reads and updates unchanged. Map and Set scenarios therefore run in a process of their own within each run, and memory workers load the plugin only for them, so other scenarios measure Immer without it. Reports record `immerMapSetEnabled`. @@ -150,7 +154,7 @@ Full comparison suites remain opt-in. Performance budgets run in separate CI job `Performance budgets` checks each PR and pushes to main on Node 24.16.0 / Ubuntu 24.04, in one job per budget group. Each job builds the actual base and head checkouts and uses this same harness for both artifacts. Measurements run sequentially on the job's runner, alternating base/candidate order and freeze/patch order across pairs. The fixed v1/Immer controls belong to comparison reports; this gate measures candidate against its immediate Git baseline so regression allowance does not accumulate relative to an old release. -[budgets.json](./budgets.json) is the versioned policy: 38 of the 99 scenarios at 1,000 rows, both freeze and patch modes, five latency pairs, and three independent memory pairs, in five groups whose jobs take 4–8 minutes each. `core` holds nine representative small/read/mutation/array scenarios; `maps` the Map scenarios, including the producers beside a Map and a Set; `sets` the other Set scenarios; `objects` the object records, class instances, the deep path, and push and insert; `apply-return-search` patch application, which runs with patches off only, returned values, and the `current()` searches. Memory budgets cover the heaviest cases: `mutation-density-100pct` and `array-reverse-nested` in `core`, and `map-update-10pct`, `set-update-10pct`, `object-update-10pct`, `class-wide-update`, `push-and-insert-reuse`, `apply-reverse`, `return-replace`, and `search-draft`. A timing regression exceeds **1.30x** and **500 ns**; sampled allocation exceeds **1.35x** and **8 KiB/output**; retained heap exceeds **1.35x** and **1 KiB/output**. Both limits must be exceeded. These tolerances accommodate noisy shared runners; review observed control ranges, as below, before tightening them. RSS is recorded but has no budget because snapshot deltas depend strongly on allocator/GC history. +[budgets.json](./budgets.json) is the versioned policy: 38 of the 101 scenarios at 1,000 rows, both freeze and patch modes, five latency pairs, and three independent memory pairs, in five groups whose jobs take 4–8 minutes each. `core` holds nine representative small/read/mutation/array scenarios; `maps` the Map scenarios, including the producers beside a Map and a Set; `sets` the other Set scenarios; `objects` the object records, class instances, the deep path, and push and insert; `apply-return-search` patch application, which runs with patches off only, returned values, and the `current()` searches. The `sparse-*` scenarios have no budget yet: the gate checks the PR base build on the same scenarios, and a Mutative build whose patches put `undefined` where holes were fails their replay checks. Memory budgets cover the heaviest cases: `mutation-density-100pct` and `array-reverse-nested` in `core`, and `map-update-10pct`, `set-update-10pct`, `object-update-10pct`, `class-wide-update`, `push-and-insert-reuse`, `apply-reverse`, `return-replace`, and `search-draft`. A timing regression exceeds **1.30x** and **500 ns**; sampled allocation exceeds **1.35x** and **8 KiB/output**; retained heap exceeds **1.35x** and **1 KiB/output**. Both limits must be exceeded. These tolerances accommodate noisy shared runners; review observed control ranges, as below, before tightening them. RSS is recorded but has no budget because snapshot deltas depend strongly on allocator/GC history. Timing compares the fastest of the five processes of each build; memory compares the medians of paired ratios and deltas. On GitHub runners about one process in six ran the array moves 20–38% slower throughout, base and candidate builds alike, so the medians of five paired ratios, which the gate compared before, failed when three or four slow processes fell to the candidate: in 4 of 113 runs from September 30 to October 8, 2026, one of them between byte-identical builds at 1.30–1.32. Compared by their fastest processes, the same runs pass all 112 that the gate can evaluate, at most 1.08 in those four. Applied to 60 runs between identical builds, a simulated candidate slowdown of 1.35x exceeds the budget in 98% of the cells and one of 1.5x in all of them, against 96% and 99% for the medians of pairs, which also flag 0.15% of the cells without a slowdown. diff --git a/perf-testing/additional-workloads.mjs b/perf-testing/additional-workloads.mjs index f610a035..d291339c 100644 --- a/perf-testing/additional-workloads.mjs +++ b/perf-testing/additional-workloads.mjs @@ -52,6 +52,33 @@ export function createAdditionalScenarios(config) { createBase: () => createArrayState({ ...config, arraySize: size, nestedArraySize: 1 }), })), + // An assignment one index past the end of an array leaves a hole before + // it; producers fill the slots of a preallocated array one by one. + { + name: 'sparse-append-gap', + steps: [ + { + type: 'bench/sparse-set', + index: config.arraySize + 1, + payload: { value: config.arraySize + 1 }, + }, + ], + createBase: () => createArrayState(config, 'shallow'), + holes: true, + }, + { + name: 'sparse-fill-slots', + steps: Array.from({ length: config.reuseStateIterations }, (_, i) => ({ + type: 'bench/sparse-set', + index: i, + payload: { value: i }, + })), + createBase: () => ({ + rows: new Array(config.arraySize), + stable: { value: 'untouched' }, + }), + holes: true, + }, ...[1, 10, 100].map((percent) => ({ name: `mutation-density-${percent}pct`, steps: [ @@ -178,6 +205,12 @@ export function reduceAdditional(state, action) { } return { ...state, rows: next }; } + case 'bench/sparse-set': { + // `slice` keeps the holes that the assignment does not fill. + const rows = state.rows.slice(); + rows[action.index] = action.payload; + return { ...state, rows }; + } case 'bench/small-object-update': return { ...state, @@ -275,6 +308,9 @@ export function applyAdditionalRecipe( case 'bench/read-length': consumeRead(draft.rows.length); break; + case 'bench/sparse-set': + draft.rows[action.index] = action.payload; + break; case 'bench/noop-empty': break; case 'bench/noop-same-value': diff --git a/perf-testing/graph.mjs b/perf-testing/graph.mjs index 531387db..f682a0a0 100644 --- a/perf-testing/graph.mjs +++ b/perf-testing/graph.mjs @@ -99,7 +99,12 @@ function childAt(parent, key) { } function applyLeaf(parent, op, key, patch) { - if (Array.isArray(parent)) { + if (Array.isArray(parent) && key === 'length') { + // Mutative lengthens an array with a length patch to leave holes. + assert.equal(op, 'replace', 'array lengths are replaced'); + assert.ok(Number.isSafeInteger(patch.value) && patch.value >= 0); + parent.length = patch.value; + } else if (Array.isArray(parent)) { const index = Number(key); assert.ok(Number.isSafeInteger(index) && index >= 0); assert.ok( diff --git a/perf-testing/graph.test.mjs b/perf-testing/graph.test.mjs index ec12757b..d82dbab9 100644 --- a/perf-testing/graph.test.mjs +++ b/perf-testing/graph.test.mjs @@ -164,3 +164,17 @@ test('replayPatches rejects patches whose target does not exist', () => { replayPatches(base, [{ op: 'replace', path: ['ids', 0], value: 1 }]) ); }); + +test('replayPatches leaves holes where a length patch lengthens an array', () => { + const next = replayPatches({ rows: [0, 1] }, [ + { op: 'replace', path: ['rows', 'length'], value: 4 }, + { op: 'replace', path: ['rows', 3], value: 3 }, + ]); + assert.equal(next.rows.length, 4); + assert.deepEqual(Object.keys(next.rows), ['0', '1', '3']); + assert.throws(() => + replayPatches({ rows: [] }, [ + { op: 'add', path: ['rows', 'length'], value: 1 }, + ]) + ); +}); diff --git a/perf-testing/scenarios.mjs b/perf-testing/scenarios.mjs index 1ba17b32..4da5e31e 100644 --- a/perf-testing/scenarios.mjs +++ b/perf-testing/scenarios.mjs @@ -17,12 +17,13 @@ import { deepFreeze } from './graph.mjs'; export function createScenarios(config, filter = '.*') { const actions = createActions(config); // kind 'apply' times patch application instead of a producer; mark is - // Mutative's option for class instances; mapSet needs Immer's MapSet plugin. + // Mutative's option for class instances; mapSet needs Immer's MapSet plugin; + // holes marks producers that leave or fill array holes. const scenario = ( name, steps, createBase = createInitialState, - { kind = 'producer', mark, mapSet = false } = {} + { kind = 'producer', mark, mapSet = false, holes = false } = {} ) => ({ name, steps, @@ -30,6 +31,7 @@ export function createScenarios(config, filter = '.*') { kind, mark, mapSet, + holes, operations: steps.length, execute(reducer, base) { let state = base; @@ -52,7 +54,7 @@ export function createScenarios(config, filter = '.*') { ); scenarios.push( ...createAdditionalScenarios(config).map((entry) => - scenario(entry.name, entry.steps, entry.createBase) + scenario(entry.name, entry.steps, entry.createBase, entry) ) ); for (const name of [ @@ -102,9 +104,12 @@ export function createScenarios(config, filter = '.*') { } // The hand-written reducer never freezes or generates patches, and patch -// application scenarios produce no patches of their own. +// application scenarios produce no patches of their own. The patches of Immer +// and Mutative v1 put `undefined` where holes were, so with patches, only the +// candidate runs the scenarios that leave or fill holes. export function supportsMode(scenario, library, autoFreeze, enablePatches) { if (scenario.kind === 'apply' && enablePatches) return false; + if (scenario.holes && enablePatches && library !== 'mutative') return false; return ( library !== 'vanilla' || (!autoFreeze && !enablePatches && scenario.kind !== 'apply') diff --git a/perf-testing/scenarios.test.mjs b/perf-testing/scenarios.test.mjs index fc14a146..8c4a6e8a 100644 --- a/perf-testing/scenarios.test.mjs +++ b/perf-testing/scenarios.test.mjs @@ -30,7 +30,24 @@ test('scenario names are unique and carry their requirements', () => { scenario.name.startsWith('class-'), `${scenario.name} mark` ); + assert.equal( + scenario.holes, + scenario.name.startsWith('sparse-'), + `${scenario.name} holes` + ); + } +}); + +test('supportsMode runs hole scenarios with patches for the candidate only', () => { + const sparse = byName('sparse-fill-slots'); + for (const autoFreeze of [false, true]) { + for (const library of ['mutative', 'mutative-v1', 'immer']) + assert.equal(supportsMode(sparse, library, autoFreeze, false), true); + assert.equal(supportsMode(sparse, 'mutative', autoFreeze, true), true); + for (const library of ['mutative-v1', 'immer', 'vanilla']) + assert.equal(supportsMode(sparse, library, autoFreeze, true), false); } + assert.equal(supportsMode(sparse, 'vanilla', false, false), true); }); test('supportsMode limits the vanilla reducer and patch application', () => { diff --git a/test/sparse-array-patches.test.ts b/test/sparse-array-patches.test.ts index bbb2da19..ff7d7682 100644 --- a/test/sparse-array-patches.test.ts +++ b/test/sparse-array-patches.test.ts @@ -364,6 +364,56 @@ test('rebuilds non-enumerable array indices too', () => { expect(restored[3]).toBe(9); }); +test('restores indices but no custom properties named like numbers', () => { + // A short suffix is checked index by index; across more than 65,536 holes, + // own keys are enumerated, where only a key past that point would count. + for (const length of [3, 70_000]) { + const base: any[] = new Array(length); + base[0] = 1; + base[length - 1] = 9; + const key = String(length - 1.5); + (base as any)[key] = 'custom'; + const [state, patches, inverse] = create( + base, + (draft) => { + draft[1] = 2; + }, + { enablePatches: true } + ); + expect( + [...patches, ...inverse].some((patch) => patch.path.includes(Number(key))) + ).toBe(false); + expect(apply(base, patches)).toStrictEqual(state); + const restored = apply(state, inverse); + expect(restored.length).toBe(length); + expect(Object.keys(restored)).toStrictEqual(['0', String(length - 1)]); + expect(restored[length - 1]).toBe(9); + } +}); + +test('filling a hole takes one patch, and its inverse patches rebuild', () => { + const base = Array.from({ length: 10 }, (_, index) => ({ index })); + delete base[0]; + const [state, patches, inverse] = create( + base, + (draft) => { + draft[0] = { index: 0 }; + }, + { enablePatches: true } + ); + expect(patches).toStrictEqual([ + { op: 'replace', path: [0], value: { index: 0 } }, + ]); + // Shorten to the hole, lengthen again, and restore the nine elements. + expect(inverse).toHaveLength(11); + const replay = apply(base, patches); + expect(replay).toStrictEqual(state); + for (let index = 1; index < 10; index += 1) { + expect(replay[index]).toBe(base[index]); + } + expect(apply(state, inverse)).toStrictEqual(base); +}); + test('manual, async and nested producers preserve sparse patches', async () => { for (const enablePatches of modes) { const base = [1, ,]; diff --git a/website/content/docs/getting-started/performance.mdx b/website/content/docs/getting-started/performance.mdx index b0edba83..4992c8c7 100644 --- a/website/content/docs/getting-started/performance.mdx +++ b/website/content/docs/getting-started/performance.mdx @@ -13,7 +13,7 @@ Mutative is about 3.6x faster than Immer with matched settings and 6.6x faster w ## Benchmark suite -The [benchmark suite](https://github.com/unadlib/mutative/tree/main/perf-testing) times 99 workloads: Immer's own performance tests, array methods, reads, Map and Set values, object records, class instances, a deep path, patch application, returned values, and searches. Its last full run measured 97 of them, and a focused run the two that return fresh data. It compares Mutative with Immer 11.1.18 and with reducers written by hand, after checking every result against those reducers. The [performance summary](https://github.com/unadlib/mutative/blob/main/perf-testing/reports/SUMMARY.md) has the complete results, the method, and their limits. +The [benchmark suite](https://github.com/unadlib/mutative/tree/main/perf-testing) times 101 workloads: Immer's own performance tests, array methods, sparse arrays, reads, Map and Set values, object records, class instances, a deep path, patch application, returned values, and searches. Its last full run measured 97 of them, and a focused run the two that return fresh data; the two sparse-array workloads came later. It compares Mutative with Immer 11.1.18 and with reducers written by hand, after checking every result against those reducers. The [performance summary](https://github.com/unadlib/mutative/blob/main/perf-testing/reports/SUMMARY.md) has the complete results, the method, and their limits. ## Mutative vs Immer From c5864526bd032b69a308199cb27bbd76b868e18a Mon Sep 17 00:00:00 2001 From: unadlib Date: Mon, 26 Oct 2026 12:28:45 -0700 Subject: [PATCH 10/13] docs: describe sparse array patches and deleting missing indices --- README.md | 5 +++-- website/content/docs/advanced-guides/migration-v2.mdx | 3 ++- website/content/docs/getting-started/installation.mdx | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 85ff7232..c5cc9b68 100644 --- a/README.md +++ b/README.md @@ -165,7 +165,7 @@ CDN The package's other ESM files read `process.env.NODE_ENV`, which bundlers and Node.js provide; a browser without a bundler needs the production file above. -Mutative has no dependencies. A production bundle of `create` alone is about 7.9 kB after Brotli compression, and one of `create`, `apply`, `current` and `original` about 8.5 kB, including patches, `Map` and `Set` support and native array methods, which need no plugins. +Mutative has no dependencies. A production bundle of `create` alone is about 8.3 kB after Brotli compression, and one of `create`, `apply`, `current` and `original` about 8.9 kB, including patches, `Map` and `Set` support and native array methods, which need no plugins. ## Usage @@ -827,6 +827,7 @@ Mutative v2 keeps the v1 API. The changes below, made since v1.3.0, can affect e - A Set draft that the recipe moves to another place, such as another key, an array, a Map, another Set or a new object, keeps its added, deleted and changed items there when its old place gets another value or is removed; v1 kept its original items. - A draft of a Set subclass changes its copy, an instance of the subclass, as Map drafts do: the subclass's own `add`, `has`, `delete` and `clear` take effect during the recipe, while the draft iterates the items in the order in which the Set holds them. v1 kept the items of a changed Set in a separate map, which bypassed those methods until it rebuilt the Set after the recipe. As a Map subclass's `set` already had to in v1, a Set subclass's `add` must store the value that it receives: an `add` that stores a copy of a draft, or of an object that holds drafts, leaves those drafts in the next state, where reading them throws. - Assigning `undefined` to a key that `delete`, `shift`, `unshift` or a shrinking `splice` removed from a draft adds the key back; v1 left a hole or kept the shorter length. +- Deleting an array index that a draft does not have, such as an index past its end, changes nothing, as in JavaScript. v1 assigned `undefined` to that index, which lengthened the array. - Assigning to a key that a draft holds as an own data property sets that property, as in JavaScript, also when a prototype defines a setter of that name. v1 called the setter through the draft instead, and assigning an own `__proto__` key, as `JSON.parse()` creates one, threw. A class instance that `mark` makes `immutable` is copied by assigning its own properties, so such a setter now runs on that copy instead of through the draft; see [Copying marked instances](https://mutative.js.org/docs/advanced-guides/mark#copying-marked-instances). - Under a `mark` that returns `mutable`, a value that the recipe assigned or moved is read back as assigned, through the draft and in `current()`; v1 returned the original value. - `current()` of a draft whose state holds a plain Set with drafts returns a snapshot; v1 threw. @@ -842,7 +843,7 @@ Mutative v2 keeps the v1 API. The changes below, made since v1.3.0, can affect e - A patch for a Map key that is an array holds the key as one path segment; v1 spread the array into the path, so applying the patch wrote to other keys. - `apply()` uses a Map key of a patch path as it is. v1 converted it to a string first, which threw for an object without a prototype. - Array patches record a change between `0` and `-0`, which the state already kept; in v1, applying the patches lost the sign. An element that stays `NaN` no longer yields a replace patch. -- When a recipe shortens an array and lengthens it again, as `draft.length = 1; draft.length = 3` does, the patches replace the indices that the longer length exposes again. In v1, applying the patches kept the removed elements at those indices, and applying the inverse patches left holes there. +- Patches keep the holes of sparse arrays apart from `undefined` elements, in both directions. When a recipe shortens an array and lengthens it again, as `draft.length = 1; draft.length = 3` does, the patches shorten and lengthen the array as well, which leaves holes at the indices that the longer length exposes again, and the inverse patches put the removed elements back. In v1, applying the patches kept the removed elements at those indices, and applying the inverse patches left holes there. v1 also put `undefined` into the holes that an array got past its end, and where a recipe filled a hole, applying the inverse patches put `undefined` there. - In strict mode, a nested `unsafe()` call no longer ends the access of the outer call; in v1, reading mutable data after it in the outer callback threw. - A producer that fails after its recipe returned, for example because the recipe changed the draft and returned another value, revokes its drafts and releases its array method cache, as a recipe that throws does; v1 left them usable. This also covers errors while inspecting a returned Proxy or calling a returned Promise's `then` method, and preserves the original error. - A draft of an array whose `Symbol.isConcatSpreadable` is false copies its elements; v1 put the whole array into the copy as its only element. diff --git a/website/content/docs/advanced-guides/migration-v2.mdx b/website/content/docs/advanced-guides/migration-v2.mdx index f462a630..2a4b96c2 100644 --- a/website/content/docs/advanced-guides/migration-v2.mdx +++ b/website/content/docs/advanced-guides/migration-v2.mdx @@ -54,6 +54,7 @@ Mutative v2 keeps the v1 API. The changes below, made since v1.3.0, can affect e - A Set draft that the recipe moves to another place, such as another key, an array, a Map, another Set or a new object, keeps its added, deleted and changed items there when its old place gets another value or is removed; v1 kept its original items. - A draft of a Set subclass changes its copy, an instance of the subclass, as Map drafts do: the subclass's own `add`, `has`, `delete` and `clear` take effect during the recipe, while the draft iterates the items in the order in which the Set holds them. v1 kept the items of a changed Set in a separate map, which bypassed those methods until it rebuilt the Set after the recipe. As a Map subclass's `set` already had to in v1, a Set subclass's `add` must store the value that it receives: an `add` that stores a copy of a draft, or of an object that holds drafts, leaves those drafts in the next state, where reading them throws. - Assigning `undefined` to a key that `delete`, `shift`, `unshift` or a shrinking `splice` removed from a draft adds the key back; v1 left a hole or kept the shorter length. +- Deleting an array index that a draft does not have, such as an index past its end, changes nothing, as in JavaScript. v1 assigned `undefined` to that index, which lengthened the array. - Assigning to a key that a draft holds as an own data property sets that property, as in JavaScript, also when a prototype defines a setter of that name. v1 called the setter through the draft instead, and assigning an own `__proto__` key, as `JSON.parse()` creates one, threw. A class instance that `mark` makes `immutable` is copied by assigning its own properties, so such a setter now runs on that copy instead of through the draft; see [Copying marked instances](/docs/advanced-guides/mark#copying-marked-instances). - Under a `mark` that returns `mutable`, a value that the recipe assigned or moved is read back as assigned, through the draft and in `current()`; v1 returned the original value. - `current()` of a draft whose state holds a plain Set with drafts returns a snapshot; v1 threw. @@ -69,7 +70,7 @@ Mutative v2 keeps the v1 API. The changes below, made since v1.3.0, can affect e - A patch for a Map key that is an array holds the key as one path segment; v1 spread the array into the path, so applying the patch wrote to other keys. - `apply()` uses a Map key of a patch path as it is. v1 converted it to a string first, which threw for an object without a prototype. - Array patches record a change between `0` and `-0`, which the state already kept; in v1, applying the patches lost the sign. An element that stays `NaN` no longer yields a replace patch. -- When a recipe shortens an array and lengthens it again, as `draft.length = 1; draft.length = 3` does, the patches replace the indices that the longer length exposes again. In v1, applying the patches kept the removed elements at those indices, and applying the inverse patches left holes there. +- Patches keep the holes of sparse arrays apart from `undefined` elements, in both directions. When a recipe shortens an array and lengthens it again, as `draft.length = 1; draft.length = 3` does, the patches shorten and lengthen the array as well, which leaves holes at the indices that the longer length exposes again, and the inverse patches put the removed elements back. In v1, applying the patches kept the removed elements at those indices, and applying the inverse patches left holes there. v1 also put `undefined` into the holes that an array got past its end, and where a recipe filled a hole, applying the inverse patches put `undefined` there. - In strict mode, a nested `unsafe()` call no longer ends the access of the outer call; in v1, reading mutable data after it in the outer callback threw. - A producer that fails after its recipe returned, for example because the recipe changed the draft and returned another value, revokes its drafts and releases its array method cache, as a recipe that throws does; v1 left them usable. This also covers errors while inspecting a returned Proxy or calling a returned Promise's `then` method, and preserves the original error. - A draft of an array whose `Symbol.isConcatSpreadable` is false copies its elements; v1 put the whole array into the copy as its only element. diff --git a/website/content/docs/getting-started/installation.mdx b/website/content/docs/getting-started/installation.mdx index cacd4d05..0b085220 100644 --- a/website/content/docs/getting-started/installation.mdx +++ b/website/content/docs/getting-started/installation.mdx @@ -9,7 +9,7 @@ description: Install Mutative from npm or load it from a CDN, and check the envi npm install mutative ``` -Mutative has no dependencies. A production bundle of `create` alone is about 7.9 kB after Brotli compression, and one of `create`, `apply`, `current` and `original` about 8.5 kB, including patches, `Map` and `Set` support and native array methods, which need no plugins. +Mutative has no dependencies. A production bundle of `create` alone is about 8.3 kB after Brotli compression, and one of `create`, `apply`, `current` and `original` about 8.9 kB, including patches, `Map` and `Set` support and native array methods, which need no plugins. ```ts import { create } from 'mutative'; From 761f37b42fad24d74c51632fdb589f0eae19f856 Mon Sep 17 00:00:00 2001 From: unadlib Date: Mon, 26 Oct 2026 12:29:13 -0700 Subject: [PATCH 11/13] style: wrap the comment on holes of moving array methods at 80 columns --- src/array.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/array.ts b/src/array.ts index 80b79607..dd316f44 100644 --- a/src/array.ts +++ b/src/array.ts @@ -116,9 +116,9 @@ function arrayState(target: ProxyDraft) { // reads as `undefined`, so an array in which the `includes` builtin finds no // `undefined` has none; that scan is fast for every kind of array. Arrays that // hold `undefined` are checked index by index with `in`, the HasProperty check -// of the native algorithms, which costs several times more per element once many array -// shapes have passed through it. Elements that are `undefined` are ordinary -// values and move natively. +// of the native algorithms, which costs several times more per element once +// many array shapes have passed through it. Elements that are `undefined` are +// ordinary values and move natively. function hasHoles(array: any[]) { if (!arrayIncludes.call(array, undefined)) return false; for (let index = 0; index < array.length; index += 1) { From 056ff1dd8e4355047962a9df67868326c3791340 Mon Sep 17 00:00:00 2001 From: unadlib Date: Tue, 27 Oct 2026 08:22:49 +0800 Subject: [PATCH 12/13] docs: distinguish v1 array deletion from the v2 regression --- README.md | 2 +- website/content/docs/advanced-guides/migration-v2.mdx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c5cc9b68..37232757 100644 --- a/README.md +++ b/README.md @@ -827,7 +827,7 @@ Mutative v2 keeps the v1 API. The changes below, made since v1.3.0, can affect e - A Set draft that the recipe moves to another place, such as another key, an array, a Map, another Set or a new object, keeps its added, deleted and changed items there when its old place gets another value or is removed; v1 kept its original items. - A draft of a Set subclass changes its copy, an instance of the subclass, as Map drafts do: the subclass's own `add`, `has`, `delete` and `clear` take effect during the recipe, while the draft iterates the items in the order in which the Set holds them. v1 kept the items of a changed Set in a separate map, which bypassed those methods until it rebuilt the Set after the recipe. As a Map subclass's `set` already had to in v1, a Set subclass's `add` must store the value that it receives: an `add` that stores a copy of a draft, or of an object that holds drafts, leaves those drafts in the next state, where reading them throws. - Assigning `undefined` to a key that `delete`, `shift`, `unshift` or a shrinking `splice` removed from a draft adds the key back; v1 left a hole or kept the shorter length. -- Deleting an array index that a draft does not have, such as an index past its end, changes nothing, as in JavaScript. v1 assigned `undefined` to that index, which lengthened the array. +- Deleting an array index that the current draft does not own changes nothing, as in JavaScript. In v1, deleting an index already absent from the original array could create an `undefined` element and, if it was past the end, lengthen the array. This also fixes the v2.0.0 regression where deleting an index removed earlier in the same recipe grew the array again; v1 kept the shortened array ([#212](https://github.com/unadlib/mutative/issues/212)). - Assigning to a key that a draft holds as an own data property sets that property, as in JavaScript, also when a prototype defines a setter of that name. v1 called the setter through the draft instead, and assigning an own `__proto__` key, as `JSON.parse()` creates one, threw. A class instance that `mark` makes `immutable` is copied by assigning its own properties, so such a setter now runs on that copy instead of through the draft; see [Copying marked instances](https://mutative.js.org/docs/advanced-guides/mark#copying-marked-instances). - Under a `mark` that returns `mutable`, a value that the recipe assigned or moved is read back as assigned, through the draft and in `current()`; v1 returned the original value. - `current()` of a draft whose state holds a plain Set with drafts returns a snapshot; v1 threw. diff --git a/website/content/docs/advanced-guides/migration-v2.mdx b/website/content/docs/advanced-guides/migration-v2.mdx index 2a4b96c2..4e4e9a7b 100644 --- a/website/content/docs/advanced-guides/migration-v2.mdx +++ b/website/content/docs/advanced-guides/migration-v2.mdx @@ -54,7 +54,7 @@ Mutative v2 keeps the v1 API. The changes below, made since v1.3.0, can affect e - A Set draft that the recipe moves to another place, such as another key, an array, a Map, another Set or a new object, keeps its added, deleted and changed items there when its old place gets another value or is removed; v1 kept its original items. - A draft of a Set subclass changes its copy, an instance of the subclass, as Map drafts do: the subclass's own `add`, `has`, `delete` and `clear` take effect during the recipe, while the draft iterates the items in the order in which the Set holds them. v1 kept the items of a changed Set in a separate map, which bypassed those methods until it rebuilt the Set after the recipe. As a Map subclass's `set` already had to in v1, a Set subclass's `add` must store the value that it receives: an `add` that stores a copy of a draft, or of an object that holds drafts, leaves those drafts in the next state, where reading them throws. - Assigning `undefined` to a key that `delete`, `shift`, `unshift` or a shrinking `splice` removed from a draft adds the key back; v1 left a hole or kept the shorter length. -- Deleting an array index that a draft does not have, such as an index past its end, changes nothing, as in JavaScript. v1 assigned `undefined` to that index, which lengthened the array. +- Deleting an array index that the current draft does not own changes nothing, as in JavaScript. In v1, deleting an index already absent from the original array could create an `undefined` element and, if it was past the end, lengthen the array. This also fixes the v2.0.0 regression where deleting an index removed earlier in the same recipe grew the array again; v1 kept the shortened array ([#212](https://github.com/unadlib/mutative/issues/212)). - Assigning to a key that a draft holds as an own data property sets that property, as in JavaScript, also when a prototype defines a setter of that name. v1 called the setter through the draft instead, and assigning an own `__proto__` key, as `JSON.parse()` creates one, threw. A class instance that `mark` makes `immutable` is copied by assigning its own properties, so such a setter now runs on that copy instead of through the draft; see [Copying marked instances](/docs/advanced-guides/mark#copying-marked-instances). - Under a `mark` that returns `mutable`, a value that the recipe assigned or moved is read back as assigned, through the draft and in `current()`; v1 returned the original value. - `current()` of a draft whose state holds a plain Set with drafts returns a snapshot; v1 threw. From 504fe6e3f78211d388a97d41cebb63efced2e173 Mon Sep 17 00:00:00 2001 From: unadlib Date: Tue, 27 Oct 2026 08:28:23 +0800 Subject: [PATCH 13/13] chore(version): update --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 46956f4b..8cf1ac15 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mutative", - "version": "2.0.0", + "version": "2.0.1", "description": "A JavaScript library for efficient immutable updates", "main": "dist/index.js", "module": "dist/mutative.esm.js",