arrayMethods.ts
This file
Path
src/plugins/arrayMethods.ts
503 lines · 15.8 KiB · TypeScript
Last changed by
Ensure array methods really do no-op correctlyMark Eriksonbefore adoptioneea464f
History of this fileTake it
feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 1–6why, one step back1import {2 PluginArrayMethods,3 latest,4 loadPlugin,5 markChanged,6 prepareCopy,Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a
line 7why, one step back7 handleCrossReference,feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 8–176why, one step back8 ProxyArrayState9} from "../internal"1011/**12 * Methods that directly modify the array in place.13 * These operate on the copy without creating per-element proxies:14 * - `push`, `pop`: Add/remove from end15 * - `shift`, `unshift`: Add/remove from start (marks all indices reassigned)16 * - `splice`: Add/remove at arbitrary position (marks all indices reassigned)17 * - `reverse`, `sort`: Reorder elements (marks all indices reassigned)18 */19type MutatingArrayMethod =20 | "push"21 | "pop"22 | "shift"23 | "unshift"24 | "splice"25 | "reverse"26 | "sort"2728/**29 * Methods that read from the array without modifying it.30 * These fall into distinct categories based on return semantics:31 *32 * **Subset operations** (return drafts - mutations propagate):33 * - `filter`, `slice`: Return array of draft proxies34 * - `find`, `findLast`: Return single draft proxy or undefined35 *36 * **Transform operations** (return base values - mutations don't track):37 * - `concat`, `flat`: Create new structures, not subsets of original38 *39 * **Primitive-returning** (no draft needed):40 * - `findIndex`, `findLastIndex`, `indexOf`, `lastIndexOf`: Return numbers41 * - `some`, `every`, `includes`: Return booleans42 * - `join`, `toString`, `toLocaleString`: Return strings43 */44type NonMutatingArrayMethod =45 | "filter"46 | "slice"47 | "concat"48 | "flat"49 | "find"50 | "findIndex"51 | "findLast"52 | "findLastIndex"53 | "some"54 | "every"55 | "indexOf"56 | "lastIndexOf"57 | "includes"58 | "join"59 | "toString"60 | "toLocaleString"6162/** Union of all array operation methods handled by the plugin. */63export type ArrayOperationMethod = MutatingArrayMethod | NonMutatingArrayMethod6465/**66 * Enables optimized array method handling for Immer drafts.67 *68 * This plugin overrides array methods to avoid unnecessary Proxy creation during iteration,69 * significantly improving performance for array-heavy operations.70 *71 * **Mutating methods** (push, pop, shift, unshift, splice, sort, reverse):72 * Operate directly on the copy without creating per-element proxies.73 *74 * **Non-mutating methods** fall into categories:75 * - **Subset operations** (filter, slice, find, findLast): Return draft proxies - mutations track76 * - **Transform operations** (concat, flat): Return base values - mutations don't track77 * - **Primitive-returning** (indexOf, includes, some, every, etc.): Return primitives78 *79 * **Important**: Callbacks for overridden methods receive base values, not drafts.80 * This is the core performance optimization.81 *82 * @example83 * ```ts84 * import { enableArrayMethods, produce } from "immer"85 *86 * enableArrayMethods()87 *88 * const next = produce(state, draft => {89 * // Optimized - no proxy creation per element90 * draft.items.sort((a, b) => a.value - b.value)91 *92 * // filter returns drafts - mutations propagate93 * const filtered = draft.items.filter(x => x.value > 5)94 * filtered[0].value = 999 // Affects draft.items[originalIndex]95 * })96 * ```97 *98 * @see https://immerjs.github.io/immer/array-methods99 */100export function enableArrayMethods() {101 const SHIFTING_METHODS = new Set<MutatingArrayMethod>(["shift", "unshift"])102103 const QUEUE_METHODS = new Set<MutatingArrayMethod>(["push", "pop"])104105 const RESULT_RETURNING_METHODS = new Set<MutatingArrayMethod>([106 ...QUEUE_METHODS,107 ...SHIFTING_METHODS108 ])109110 const REORDERING_METHODS = new Set<MutatingArrayMethod>(["reverse", "sort"])111112 // Optimized method detection using array-based lookup113 const MUTATING_METHODS = new Set<MutatingArrayMethod>([114 ...RESULT_RETURNING_METHODS,115 ...REORDERING_METHODS,116 "splice"117 ])118119 const FIND_METHODS = new Set<NonMutatingArrayMethod>(["find", "findLast"])120121 const NON_MUTATING_METHODS = new Set<NonMutatingArrayMethod>([122 "filter",123 "slice",124 "concat",125 "flat",126 ...FIND_METHODS,127 "findIndex",128 "findLastIndex",129 "some",130 "every",131 "indexOf",132 "lastIndexOf",133 "includes",134 "join",135 "toString",136 "toLocaleString"137 ])138139 // Type guard for method detection140 function isMutatingArrayMethod(141 method: string142 ): method is MutatingArrayMethod {143 return MUTATING_METHODS.has(method as any)144 }145146 function isNonMutatingArrayMethod(147 method: string148 ): method is NonMutatingArrayMethod {149 return NON_MUTATING_METHODS.has(method as any)150 }151152 function isArrayOperationMethod(153 method: string154 ): method is ArrayOperationMethod {155 return isMutatingArrayMethod(method) || isNonMutatingArrayMethod(method)156 }157158 function enterOperation(159 state: ProxyArrayState,160 method: ArrayOperationMethod161 ) {162 state.operationMethod = method163 }164165 function exitOperation(state: ProxyArrayState) {166 state.operationMethod = undefined167 }168169 // Shared utility functions for array method handlers170 function executeArrayMethod<T>(171 state: ProxyArrayState,172 operation: () => T,173 markLength = true174 ): T {175 prepareCopy(state)176 const result = operation()fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
lines 177–189why, one step back177 markArrayChanged(state, markLength)178 return result179 }180181 /**182 * Marks the array (and its ancestors) as modified after a mutating operation.183 *184 * Kept separate from `executeArrayMethod` so that operations which turn out to185 * be no-ops (e.g. `push()` with no arguments, `splice(i, 0)`, `pop()`/`shift()`186 * on an empty array) can prepare a copy but skip marking, preserving Immer's187 * structural-sharing guarantee that a change-free producer returns the base.188 */189 function markArrayChanged(state: ProxyArrayState, markLength = true) {feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 190–195why, one step back190 markChanged(state)191 if (markLength) state.assigned_!.set("length", true)192 }193194 function markAllIndicesReassigned(state: ProxyArrayState) {195 state.allIndicesReassigned_ = truefix: draft relocated base refs after reverse/sort in array-methods plugin (#1255)spokodevbefore adoptiona73672a
line 196why, one step back196 state.baseRefs_ = new Set(state.base_)feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 197–206why, one step back197 }198199 function normalizeSliceIndex(index: number, length: number): number {200 if (index < 0) {201 return Math.max(length + index, 0)202 }203 return Math.min(index, length)204 }205206 /**Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a
lines 207–216why, one step back207 * Calls handleCrossReference for each value being inserted into the array,208 * and marks the corresponding indices as assigned in `assigned_`.209 *210 * This ensures nested drafts inside inserted values (e.g. from spreading211 * a draft object) are properly finalized, matching the behavior of the212 * proxy set trap which calls handleCrossReference on every assignment.213 *214 * Without this, values containing draft proxies (like `{...state[0]}`)215 * pushed via the array methods plugin would have their nested drafts216 * revoked during finalization without being replaced by final values.Merge pull request #1283 from Jaybhade/fix/array-methods-assigned-index-keyMark Eriksonbefore adoptiond2c158f
lines 217–221why, one step back217 *218 * The index is stringified because the proxy traps only ever see property219 * names, so `assigned_` is keyed by string everywhere else. A numeric key220 * would be invisible to the readers that look indices up by name, such as221 * patch generation.Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a
lines 222–228why, one step back222 */223 function handleInsertedValues(224 state: ProxyArrayState,225 startIndex: number,226 values: any[]227 ) {228 for (let i = 0; i < values.length; i++) {Merge pull request #1283 from Jaybhade/fix/array-methods-assigned-index-keyMark Eriksonbefore adoptiond2c158f
line 229why, one step back229 const index = "" + (startIndex + i)Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a
lines 230–235why, one step back230 state.assigned_!.set(index, true)231 handleCrossReference(state, index, values[i])232 }233 }234235 /**feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 236–248why, one step back236 * Handles mutating operations that add/remove elements (push, pop, shift, unshift, splice).237 *238 * Operates directly on `state.copy_` without creating per-element proxies.239 * For shifting methods (shift, unshift), marks all indices as reassigned since240 * indices shift.241 *242 * @returns For push/pop/shift/unshift: the native method result. For others: the draft.243 */244 function handleSimpleOperation(245 state: ProxyArrayState,246 method: string,247 args: any[]248 ) {Ensure array methods really do no-op correctlyMark Eriksonbefore adoptioneea464f
lines 249–260why, one step back249 // Detect no-op calls before creating a copy so structural sharing is250 // preserved: push/unshift with no arguments add nothing, and pop/shift251 // on an empty array remove nothing. The check must happen before252 // prepareCopy - a stray copy_ on an unmodified state would be picked253 // up by finalization of a parent Set and break identity there.254 const isInsert = method === "push" || method === "unshift"255 if (isInsert ? args.length === 0 : latest(state).length === 0) {256 // Match the native return values: push/unshift return the257 // (unchanged) length, pop/shift on an empty array return undefined258 return isInsert ? latest(state).length : undefined259 }260fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
line 261why, one step back261 prepareCopy(state)Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a
line 262why, one step back262fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
lines 263–265why, one step back263 // For push/unshift, capture the length before the operation264 // so we can compute insertion indices for handleCrossReference265 const lengthBefore = state.copy_!.lengthfeat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
line 266why, one step back266fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
lines 267–268why, one step back267 const result = (state.copy_! as any)[method](...args)268Ensure array methods really do no-op correctlyMark Eriksonbefore adoptioneea464f
line 269why, one step back269 markArrayChanged(state)fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
line 270why, one step back270Ensure array methods really do no-op correctlyMark Eriksonbefore adoptioneea464f
lines 271–274why, one step back271 // Handle index reassignment for shifting methods272 if (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {273 markAllIndicesReassigned(state)274 }fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
line 275why, one step back275Ensure array methods really do no-op correctlyMark Eriksonbefore adoptioneea464f
lines 276–281why, one step back276 // Handle cross-references for newly inserted values.277 // push appends at the end, unshift inserts at the beginning.278 if (method === "push") {279 handleInsertedValues(state, lengthBefore, args)280 } else if (method === "unshift") {281 handleInsertedValues(state, 0, args)fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
line 282why, one step back282 }Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a
line 283why, one step back283fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
lines 284–287why, one step back284 // Return appropriate value based on method285 return RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)286 ? result287 : state.draft_feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 288–352why, one step back288 }289290 /**291 * Handles reordering operations (reverse, sort) that change element order.292 *293 * Operates directly on `state.copy_` and marks all indices as reassigned294 * since element positions change. Does not mark length as changed since295 * these operations preserve array length.296 *297 * @returns The draft proxy for method chaining.298 */299 function handleReorderingOperation(300 state: ProxyArrayState,301 method: string,302 args: any[]303 ) {304 return executeArrayMethod(305 state,306 () => {307 ;(state.copy_! as any)[method](...args)308 markAllIndicesReassigned(state)309 return state.draft_310 },311 false312 ) // Don't mark length as changed313 }314315 /**316 * Creates an interceptor function for a specific array method.317 *318 * The interceptor wraps array method calls to:319 * 1. Set `state.operationMethod` flag during execution (allows proxy `get` trap320 * to detect we're inside an optimized method and skip proxy creation)321 * 2. Route to appropriate handler based on method type322 * 3. Clean up the operation flag in `finally` block323 *324 * The `operationMethod` flag is the key mechanism that enables the proxy's `get`325 * trap to return base values instead of creating nested proxies during iteration.326 *327 * @param state - The proxy array state328 * @param originalMethod - Name of the array method being intercepted329 * @returns Interceptor function that handles the method call330 */331 function createMethodInterceptor(332 state: ProxyArrayState,333 originalMethod: string334 ) {335 return function interceptedMethod(...args: any[]) {336 // Enter operation mode - this flag tells the proxy's get trap to return337 // base values instead of creating nested proxies during iteration338 const method = originalMethod as ArrayOperationMethod339 enterOperation(state, method)340341 try {342 // Check if this is a mutating method343 if (isMutatingArrayMethod(method)) {344 // Direct method dispatch - no configuration lookup needed345 if (RESULT_RETURNING_METHODS.has(method)) {346 return handleSimpleOperation(state, method, args)347 }348 if (REORDERING_METHODS.has(method)) {349 return handleReorderingOperation(state, method, args)350 }351352 if (method === "splice") {fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
line 353why, one step back353 const insertCount = args.length > 2 ? args.length - 2 : 0Ensure array methods really do no-op correctlyMark Eriksonbefore adoptioneea464f
lines 354–374why, one step back354355 // Detect no-op calls before creating a copy so structural356 // sharing is preserved (see handleSimpleOperation). A splice357 // removes nothing when called with no arguments, when the358 // normalized start is at/past the end, or when the delete359 // count coerces to less than 1. splice(start) with a single360 // argument removes everything from start onwards, so it must361 // not match. Exotic arguments that slip through are caught362 // by the post-copy check below.363 if (insertCount === 0) {364 const length = latest(state).length365 if (366 args.length === 0 ||367 normalizeSliceIndex(args[0] ?? 0, length) === length ||368 (args.length > 1 && !(args[1] >= 1))369 ) {370 return []371 }372 }373374 prepareCopy(state)fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
lines 375–376why, one step back375 const res = state.copy_!.splice(376 ...(args as [number, number, ...any[]])feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
line 377why, one step back377 )fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
line 378why, one step back378Ensure array methods really do no-op correctlyMark Eriksonbefore adoptioneea464f
lines 379–381why, one step back379 // Backstop for exotic arguments the pre-check above missed:380 // if nothing was removed and nothing inserted, the array is381 // unchanged and must not be marked as modified.fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
lines 382–386why, one step back382 if (res.length === 0 && insertCount === 0) {383 return res384 }385386 markArrayChanged(state)feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
line 387why, one step back387 markAllIndicesReassigned(state)Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a
line 388why, one step back388 // Handle cross-references for inserted values (args from index 2+)fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
line 389why, one step back389 if (insertCount > 0) {Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a
lines 390–395why, one step back390 const startIndex = normalizeSliceIndex(391 args[0] ?? 0,392 state.copy_!.length393 )394 handleInsertedValues(state, startIndex, args.slice(2))395 }feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 396–503why, one step back396 return res397 }398 } else {399 // Handle non-mutating methods400 return handleNonMutatingOperation(state, method, args)401 }402 } finally {403 // Always exit operation mode - must be in finally to handle exceptions404 exitOperation(state)405 }406 }407 }408409 /**410 * Handles non-mutating array methods with different return semantics.411 *412 * **Subset operations** return draft proxies for mutation tracking:413 * - `filter`, `slice`: Return `state.draft_[i]` for each selected element414 * - `find`, `findLast`: Return `state.draft_[i]` for the found element415 *416 * This allows mutations on returned elements to propagate back to the draft:417 * ```ts418 * const filtered = draft.items.filter(x => x.value > 5)419 * filtered[0].value = 999 // Mutates draft.items[originalIndex]420 * ```421 *422 * **Transform operations** return base values (no draft tracking):423 * - `concat`, `flat`: These create NEW arrays rather than selecting subsets.424 * Since the result structure differs from the original, tracking mutations425 * back to specific draft indices would be impractical/impossible.426 *427 * **Primitive operations** return the native result directly:428 * - `indexOf`, `includes`, `some`, `every`, `join`, etc.429 *430 * @param state - The proxy array state431 * @param method - The non-mutating method name432 * @param args - Arguments passed to the method433 * @returns Drafts for subset operations, base values for transforms, primitives otherwise434 */435 function handleNonMutatingOperation(436 state: ProxyArrayState,437 method: NonMutatingArrayMethod,438 args: any[]439 ) {440 const source = latest(state)441442 // Methods that return arrays with selected items - need to return drafts443 if (method === "filter") {444 const predicate = args[0]445 const result: any[] = []446447 // First pass: call predicate on base values to determine which items pass448 for (let i = 0; i < source.length; i++) {449 if (predicate(source[i], i, source)) {450 // Only create draft for items that passed the predicate451 result.push(state.draft_[i])452 }453 }454455 return result456 }457458 if (FIND_METHODS.has(method)) {459 const predicate = args[0]460 const isForward = method === "find"461 const step = isForward ? 1 : -1462 const start = isForward ? 0 : source.length - 1463464 for (let i = start; i >= 0 && i < source.length; i += step) {465 if (predicate(source[i], i, source)) {466 return state.draft_[i]467 }468 }469 return undefined470 }471472 if (method === "slice") {473 const rawStart = args[0] ?? 0474 const rawEnd = args[1] ?? source.length475476 // Normalize negative indices477 const start = normalizeSliceIndex(rawStart, source.length)478 const end = normalizeSliceIndex(rawEnd, source.length)479480 const result: any[] = []481482 // Return drafts for items in the slice range483 for (let i = start; i < end; i++) {484 result.push(state.draft_[i])485 }486487 return result488 }489490 // For other methods, call on base array directly:491 // - indexOf, includes, join, toString: Return primitives, no draft needed492 // - concat, flat: Return NEW arrays (not subsets). Elements are base values.493 // This is intentional - concat/flat create new data structures rather than494 // selecting subsets of the original, making draft tracking impractical.495 return source[method as keyof typeof Array.prototype](...args)496 }497498 loadPlugin(PluginArrayMethods, {499 createMethodInterceptor,500 isArrayOperationMethod,501 isMutatingArrayMethod502 })503}