Skip to content
Myr

arrayMethods.ts

This file

Path

src/plugins/arrayMethods.ts

446 lines · 13.6 KiB · TypeScript

Last changed by

fix: key inserted array indices by name in the array-methods pluginjaybhadebefore adoptione3df956

History of this file

Take it

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 1–6why, one step back
1import {
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 back
7 handleCrossReference,

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 8–183why, one step back
8 ProxyArrayState
9} 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()177 markChanged(state)178 if (markLength) state.assigned_!.set("length", true)179 return result180 }181182 function markAllIndicesReassigned(state: ProxyArrayState) {183 state.allIndicesReassigned_ = true

fix: draft relocated base refs after reverse/sort in array-methods plugin (#1255)spokodevbefore adoptiona73672a

line 184why, one step back
184 state.baseRefs_ = new Set(state.base_)

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 185–194why, one step back
185 }
186187 function normalizeSliceIndex(index: number, length: number): number {188 if (index < 0) {189 return Math.max(length + index, 0)190 }191 return Math.min(index, length)192 }193194 /**

Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a

lines 195–204why, one step back
195 * Calls handleCrossReference for each value being inserted into the array,
196 * and marks the corresponding indices as assigned in `assigned_`.197 *198 * This ensures nested drafts inside inserted values (e.g. from spreading199 * a draft object) are properly finalized, matching the behavior of the200 * proxy set trap which calls handleCrossReference on every assignment.201 *202 * Without this, values containing draft proxies (like `{...state[0]}`)203 * pushed via the array methods plugin would have their nested drafts204 * revoked during finalization without being replaced by final values.

fix: key inserted array indices by name in the array-methods pluginjaybhadebefore adoptione3df956

lines 205–209why, one step back
205 *
206 * The index is stringified because the proxy traps only ever see property207 * names, so `assigned_` is keyed by string everywhere else. A numeric key208 * would be invisible to the readers that look indices up by name, such as209 * patch generation.

Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a

lines 210–216why, one step back
210 */
211 function handleInsertedValues(212 state: ProxyArrayState,213 startIndex: number,214 values: any[]215 ) {216 for (let i = 0; i < values.length; i++) {

fix: key inserted array indices by name in the array-methods pluginjaybhadebefore adoptione3df956

line 217why, one step back
217 const index = "" + (startIndex + i)

Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a

lines 218–223why, one step back
218 state.assigned_!.set(index, true)
219 handleCrossReference(state, index, values[i])220 }221 }222223 /**

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 224–237why, one step back
224 * Handles mutating operations that add/remove elements (push, pop, shift, unshift, splice).
225 *226 * Operates directly on `state.copy_` without creating per-element proxies.227 * For shifting methods (shift, unshift), marks all indices as reassigned since228 * indices shift.229 *230 * @returns For push/pop/shift/unshift: the native method result. For others: the draft.231 */232 function handleSimpleOperation(233 state: ProxyArrayState,234 method: string,235 args: any[]236 ) {237 return executeArrayMethod(state, () => {

Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a

lines 238–241why, one step back
238 // For push/unshift, capture the length before the operation
239 // so we can compute insertion indices for handleCrossReference240 const lengthBefore = state.copy_!.length241

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 242–248why, one step back
242 const result = (state.copy_! as any)[method](...args)
243244 // Handle index reassignment for shifting methods245 if (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {246 markAllIndicesReassigned(state)247 }248

Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a

lines 249–256why, one step back
249 // Handle cross-references for newly inserted values.
250 // push appends at the end, unshift inserts at the beginning.251 if (method === "push" && args.length > 0) {252 handleInsertedValues(state, lengthBefore, args)253 } else if (method === "unshift" && args.length > 0) {254 handleInsertedValues(state, 0, args)255 }256

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 257–330why, one step back
257 // Return appropriate value based on method
258 return RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)259 ? result260 : state.draft_261 })262 }263264 /**265 * Handles reordering operations (reverse, sort) that change element order.266 *267 * Operates directly on `state.copy_` and marks all indices as reassigned268 * since element positions change. Does not mark length as changed since269 * these operations preserve array length.270 *271 * @returns The draft proxy for method chaining.272 */273 function handleReorderingOperation(274 state: ProxyArrayState,275 method: string,276 args: any[]277 ) {278 return executeArrayMethod(279 state,280 () => {281 ;(state.copy_! as any)[method](...args)282 markAllIndicesReassigned(state)283 return state.draft_284 },285 false286 ) // Don't mark length as changed287 }288289 /**290 * Creates an interceptor function for a specific array method.291 *292 * The interceptor wraps array method calls to:293 * 1. Set `state.operationMethod` flag during execution (allows proxy `get` trap294 * to detect we're inside an optimized method and skip proxy creation)295 * 2. Route to appropriate handler based on method type296 * 3. Clean up the operation flag in `finally` block297 *298 * The `operationMethod` flag is the key mechanism that enables the proxy's `get`299 * trap to return base values instead of creating nested proxies during iteration.300 *301 * @param state - The proxy array state302 * @param originalMethod - Name of the array method being intercepted303 * @returns Interceptor function that handles the method call304 */305 function createMethodInterceptor(306 state: ProxyArrayState,307 originalMethod: string308 ) {309 return function interceptedMethod(...args: any[]) {310 // Enter operation mode - this flag tells the proxy's get trap to return311 // base values instead of creating nested proxies during iteration312 const method = originalMethod as ArrayOperationMethod313 enterOperation(state, method)314315 try {316 // Check if this is a mutating method317 if (isMutatingArrayMethod(method)) {318 // Direct method dispatch - no configuration lookup needed319 if (RESULT_RETURNING_METHODS.has(method)) {320 return handleSimpleOperation(state, method, args)321 }322 if (REORDERING_METHODS.has(method)) {323 return handleReorderingOperation(state, method, args)324 }325326 if (method === "splice") {327 const res = executeArrayMethod(state, () =>328 state.copy_!.splice(...(args as [number, number, ...any[]]))329 )330 markAllIndicesReassigned(state)

Merge pull request #1210 from immerjs/bugfix/1209-array-plugin-nested-draftsMark Eriksonbefore adoptioncdccf1a

lines 331–338why, one step back
331 // Handle cross-references for inserted values (args from index 2+)
332 if (args.length > 2) {333 const startIndex = normalizeSliceIndex(334 args[0] ?? 0,335 state.copy_!.length336 )337 handleInsertedValues(state, startIndex, args.slice(2))338 }

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 339–446why, one step back
339 return res
340 }341 } else {342 // Handle non-mutating methods343 return handleNonMutatingOperation(state, method, args)344 }345 } finally {346 // Always exit operation mode - must be in finally to handle exceptions347 exitOperation(state)348 }349 }350 }351352 /**353 * Handles non-mutating array methods with different return semantics.354 *355 * **Subset operations** return draft proxies for mutation tracking:356 * - `filter`, `slice`: Return `state.draft_[i]` for each selected element357 * - `find`, `findLast`: Return `state.draft_[i]` for the found element358 *359 * This allows mutations on returned elements to propagate back to the draft:360 * ```ts361 * const filtered = draft.items.filter(x => x.value > 5)362 * filtered[0].value = 999 // Mutates draft.items[originalIndex]363 * ```364 *365 * **Transform operations** return base values (no draft tracking):366 * - `concat`, `flat`: These create NEW arrays rather than selecting subsets.367 * Since the result structure differs from the original, tracking mutations368 * back to specific draft indices would be impractical/impossible.369 *370 * **Primitive operations** return the native result directly:371 * - `indexOf`, `includes`, `some`, `every`, `join`, etc.372 *373 * @param state - The proxy array state374 * @param method - The non-mutating method name375 * @param args - Arguments passed to the method376 * @returns Drafts for subset operations, base values for transforms, primitives otherwise377 */378 function handleNonMutatingOperation(379 state: ProxyArrayState,380 method: NonMutatingArrayMethod,381 args: any[]382 ) {383 const source = latest(state)384385 // Methods that return arrays with selected items - need to return drafts386 if (method === "filter") {387 const predicate = args[0]388 const result: any[] = []389390 // First pass: call predicate on base values to determine which items pass391 for (let i = 0; i < source.length; i++) {392 if (predicate(source[i], i, source)) {393 // Only create draft for items that passed the predicate394 result.push(state.draft_[i])395 }396 }397398 return result399 }400401 if (FIND_METHODS.has(method)) {402 const predicate = args[0]403 const isForward = method === "find"404 const step = isForward ? 1 : -1405 const start = isForward ? 0 : source.length - 1406407 for (let i = start; i >= 0 && i < source.length; i += step) {408 if (predicate(source[i], i, source)) {409 return state.draft_[i]410 }411 }412 return undefined413 }414415 if (method === "slice") {416 const rawStart = args[0] ?? 0417 const rawEnd = args[1] ?? source.length418419 // Normalize negative indices420 const start = normalizeSliceIndex(rawStart, source.length)421 const end = normalizeSliceIndex(rawEnd, source.length)422423 const result: any[] = []424425 // Return drafts for items in the slice range426 for (let i = start; i < end; i++) {427 result.push(state.draft_[i])428 }429430 return result431 }432433 // For other methods, call on base array directly:434 // - indexOf, includes, join, toString: Return primitives, no draft needed435 // - concat, flat: Return NEW arrays (not subsets). Elements are base values.436 // This is intentional - concat/flat create new data structures rather than437 // selecting subsets of the original, making draft tracking impractical.438 return source[method as keyof typeof Array.prototype](...args)439 }440441 loadPlugin(PluginArrayMethods, {442 createMethodInterceptor,443 isArrayOperationMethod,444 isMutatingArrayMethod445 })446}