arrayMethods.ts
This file
Path
src/plugins/arrayMethods.ts
480 lines · 14.7 KiB · TypeScript
Last changed by
fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
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 ) {fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
line 249why, one step back249 prepareCopy(state)Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a
line 250why, one step back250fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
lines 251–253why, one step back251 // For push/unshift, capture the length before the operation252 // so we can compute insertion indices for handleCrossReference253 const lengthBefore = state.copy_!.lengthfeat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
line 254why, one step back254fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
lines 255–267why, one step back255 const result = (state.copy_! as any)[method](...args)256257 // Detect no-op calls so structural sharing is preserved:258 // push/unshift with no arguments add nothing, and pop/shift on an259 // empty array remove nothing. In those cases the array is unchanged.260 const changed =261 method === "push" || method === "unshift"262 ? args.length > 0263 : lengthBefore > 0 // pop / shift264265 if (changed) {266 markArrayChanged(state)267feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 268–272why, one step back268 // Handle index reassignment for shifting methods269 if (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {270 markAllIndicesReassigned(state)271 }272Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a
lines 273–274why, one step back273 // Handle cross-references for newly inserted values.274 // push appends at the end, unshift inserts at the beginning.fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
line 275why, one step back275 if (method === "push") {Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a
line 276why, one step back276 handleInsertedValues(state, lengthBefore, args)fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
line 277why, one step back277 } else if (method === "unshift") {Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a
lines 278–279why, one step back278 handleInsertedValues(state, 0, args)279 }fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
line 280why, one step back280 }Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a
line 281why, one step back281fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
lines 282–285why, one step back282 // Return appropriate value based on method283 return RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)284 ? result285 : state.draft_feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 286–350why, one step back286 }287288 /**289 * Handles reordering operations (reverse, sort) that change element order.290 *291 * Operates directly on `state.copy_` and marks all indices as reassigned292 * since element positions change. Does not mark length as changed since293 * these operations preserve array length.294 *295 * @returns The draft proxy for method chaining.296 */297 function handleReorderingOperation(298 state: ProxyArrayState,299 method: string,300 args: any[]301 ) {302 return executeArrayMethod(303 state,304 () => {305 ;(state.copy_! as any)[method](...args)306 markAllIndicesReassigned(state)307 return state.draft_308 },309 false310 ) // Don't mark length as changed311 }312313 /**314 * Creates an interceptor function for a specific array method.315 *316 * The interceptor wraps array method calls to:317 * 1. Set `state.operationMethod` flag during execution (allows proxy `get` trap318 * to detect we're inside an optimized method and skip proxy creation)319 * 2. Route to appropriate handler based on method type320 * 3. Clean up the operation flag in `finally` block321 *322 * The `operationMethod` flag is the key mechanism that enables the proxy's `get`323 * trap to return base values instead of creating nested proxies during iteration.324 *325 * @param state - The proxy array state326 * @param originalMethod - Name of the array method being intercepted327 * @returns Interceptor function that handles the method call328 */329 function createMethodInterceptor(330 state: ProxyArrayState,331 originalMethod: string332 ) {333 return function interceptedMethod(...args: any[]) {334 // Enter operation mode - this flag tells the proxy's get trap to return335 // base values instead of creating nested proxies during iteration336 const method = originalMethod as ArrayOperationMethod337 enterOperation(state, method)338339 try {340 // Check if this is a mutating method341 if (isMutatingArrayMethod(method)) {342 // Direct method dispatch - no configuration lookup needed343 if (RESULT_RETURNING_METHODS.has(method)) {344 return handleSimpleOperation(state, method, args)345 }346 if (REORDERING_METHODS.has(method)) {347 return handleReorderingOperation(state, method, args)348 }349350 if (method === "splice") {fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
lines 351–354why, one step back351 prepareCopy(state)352 const insertCount = args.length > 2 ? args.length - 2 : 0353 const res = state.copy_!.splice(354 ...(args as [number, number, ...any[]])feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
line 355why, one step back355 )fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
lines 356–363why, one step back356357 // A splice that removes and inserts nothing leaves the array358 // unchanged, so structural sharing must be preserved.359 if (res.length === 0 && insertCount === 0) {360 return res361 }362363 markArrayChanged(state)feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
line 364why, one step back364 markAllIndicesReassigned(state)Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a
line 365why, one step back365 // Handle cross-references for inserted values (args from index 2+)fix: preserve structural sharing for no-op array-methods callsmaximilliangrandbefore adoption0c3efdd
line 366why, one step back366 if (insertCount > 0) {Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a
lines 367–372why, one step back367 const startIndex = normalizeSliceIndex(368 args[0] ?? 0,369 state.copy_!.length370 )371 handleInsertedValues(state, startIndex, args.slice(2))372 }feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 373–480why, one step back373 return res374 }375 } else {376 // Handle non-mutating methods377 return handleNonMutatingOperation(state, method, args)378 }379 } finally {380 // Always exit operation mode - must be in finally to handle exceptions381 exitOperation(state)382 }383 }384 }385386 /**387 * Handles non-mutating array methods with different return semantics.388 *389 * **Subset operations** return draft proxies for mutation tracking:390 * - `filter`, `slice`: Return `state.draft_[i]` for each selected element391 * - `find`, `findLast`: Return `state.draft_[i]` for the found element392 *393 * This allows mutations on returned elements to propagate back to the draft:394 * ```ts395 * const filtered = draft.items.filter(x => x.value > 5)396 * filtered[0].value = 999 // Mutates draft.items[originalIndex]397 * ```398 *399 * **Transform operations** return base values (no draft tracking):400 * - `concat`, `flat`: These create NEW arrays rather than selecting subsets.401 * Since the result structure differs from the original, tracking mutations402 * back to specific draft indices would be impractical/impossible.403 *404 * **Primitive operations** return the native result directly:405 * - `indexOf`, `includes`, `some`, `every`, `join`, etc.406 *407 * @param state - The proxy array state408 * @param method - The non-mutating method name409 * @param args - Arguments passed to the method410 * @returns Drafts for subset operations, base values for transforms, primitives otherwise411 */412 function handleNonMutatingOperation(413 state: ProxyArrayState,414 method: NonMutatingArrayMethod,415 args: any[]416 ) {417 const source = latest(state)418419 // Methods that return arrays with selected items - need to return drafts420 if (method === "filter") {421 const predicate = args[0]422 const result: any[] = []423424 // First pass: call predicate on base values to determine which items pass425 for (let i = 0; i < source.length; i++) {426 if (predicate(source[i], i, source)) {427 // Only create draft for items that passed the predicate428 result.push(state.draft_[i])429 }430 }431432 return result433 }434435 if (FIND_METHODS.has(method)) {436 const predicate = args[0]437 const isForward = method === "find"438 const step = isForward ? 1 : -1439 const start = isForward ? 0 : source.length - 1440441 for (let i = start; i >= 0 && i < source.length; i += step) {442 if (predicate(source[i], i, source)) {443 return state.draft_[i]444 }445 }446 return undefined447 }448449 if (method === "slice") {450 const rawStart = args[0] ?? 0451 const rawEnd = args[1] ?? source.length452453 // Normalize negative indices454 const start = normalizeSliceIndex(rawStart, source.length)455 const end = normalizeSliceIndex(rawEnd, source.length)456457 const result: any[] = []458459 // Return drafts for items in the slice range460 for (let i = start; i < end; i++) {461 result.push(state.draft_[i])462 }463464 return result465 }466467 // For other methods, call on base array directly:468 // - indexOf, includes, join, toString: Return primitives, no draft needed469 // - concat, flat: Return NEW arrays (not subsets). Elements are base values.470 // This is intentional - concat/flat create new data structures rather than471 // selecting subsets of the original, making draft tracking impractical.472 return source[method as keyof typeof Array.prototype](...args)473 }474475 loadPlugin(PluginArrayMethods, {476 createMethodInterceptor,477 isArrayOperationMethod,478 isMutatingArrayMethod479 })480}