Skip to content
Myr

arrayMethods.ts

This file

Path

src/plugins/arrayMethods.ts

441 lines · 13.3 KiB · TypeScript

Last changed by

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

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–218why, 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.205 */206 function handleInsertedValues(207 state: ProxyArrayState,208 startIndex: number,209 values: any[]210 ) {211 for (let i = 0; i < values.length; i++) {212 const index = startIndex + i213 state.assigned_!.set(index, true)214 handleCrossReference(state, index, values[i])215 }216 }217218 /**

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

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

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

lines 233–236why, one step back
233 // For push/unshift, capture the length before the operation
234 // so we can compute insertion indices for handleCrossReference235 const lengthBefore = state.copy_!.length236

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

lines 237–243why, one step back
237 const result = (state.copy_! as any)[method](...args)
238239 // Handle index reassignment for shifting methods240 if (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {241 markAllIndicesReassigned(state)242 }243

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

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

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

lines 252–325why, one step back
252 // Return appropriate value based on method
253 return RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)254 ? result255 : state.draft_256 })257 }258259 /**260 * Handles reordering operations (reverse, sort) that change element order.261 *262 * Operates directly on `state.copy_` and marks all indices as reassigned263 * since element positions change. Does not mark length as changed since264 * these operations preserve array length.265 *266 * @returns The draft proxy for method chaining.267 */268 function handleReorderingOperation(269 state: ProxyArrayState,270 method: string,271 args: any[]272 ) {273 return executeArrayMethod(274 state,275 () => {276 ;(state.copy_! as any)[method](...args)277 markAllIndicesReassigned(state)278 return state.draft_279 },280 false281 ) // Don't mark length as changed282 }283284 /**285 * Creates an interceptor function for a specific array method.286 *287 * The interceptor wraps array method calls to:288 * 1. Set `state.operationMethod` flag during execution (allows proxy `get` trap289 * to detect we're inside an optimized method and skip proxy creation)290 * 2. Route to appropriate handler based on method type291 * 3. Clean up the operation flag in `finally` block292 *293 * The `operationMethod` flag is the key mechanism that enables the proxy's `get`294 * trap to return base values instead of creating nested proxies during iteration.295 *296 * @param state - The proxy array state297 * @param originalMethod - Name of the array method being intercepted298 * @returns Interceptor function that handles the method call299 */300 function createMethodInterceptor(301 state: ProxyArrayState,302 originalMethod: string303 ) {304 return function interceptedMethod(...args: any[]) {305 // Enter operation mode - this flag tells the proxy's get trap to return306 // base values instead of creating nested proxies during iteration307 const method = originalMethod as ArrayOperationMethod308 enterOperation(state, method)309310 try {311 // Check if this is a mutating method312 if (isMutatingArrayMethod(method)) {313 // Direct method dispatch - no configuration lookup needed314 if (RESULT_RETURNING_METHODS.has(method)) {315 return handleSimpleOperation(state, method, args)316 }317 if (REORDERING_METHODS.has(method)) {318 return handleReorderingOperation(state, method, args)319 }320321 if (method === "splice") {322 const res = executeArrayMethod(state, () =>323 state.copy_!.splice(...(args as [number, number, ...any[]]))324 )325 markAllIndicesReassigned(state)

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

lines 326–333why, one step back
326 // Handle cross-references for inserted values (args from index 2+)
327 if (args.length > 2) {328 const startIndex = normalizeSliceIndex(329 args[0] ?? 0,330 state.copy_!.length331 )332 handleInsertedValues(state, startIndex, args.slice(2))333 }

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

lines 334–441why, one step back
334 return res
335 }336 } else {337 // Handle non-mutating methods338 return handleNonMutatingOperation(state, method, args)339 }340 } finally {341 // Always exit operation mode - must be in finally to handle exceptions342 exitOperation(state)343 }344 }345 }346347 /**348 * Handles non-mutating array methods with different return semantics.349 *350 * **Subset operations** return draft proxies for mutation tracking:351 * - `filter`, `slice`: Return `state.draft_[i]` for each selected element352 * - `find`, `findLast`: Return `state.draft_[i]` for the found element353 *354 * This allows mutations on returned elements to propagate back to the draft:355 * ```ts356 * const filtered = draft.items.filter(x => x.value > 5)357 * filtered[0].value = 999 // Mutates draft.items[originalIndex]358 * ```359 *360 * **Transform operations** return base values (no draft tracking):361 * - `concat`, `flat`: These create NEW arrays rather than selecting subsets.362 * Since the result structure differs from the original, tracking mutations363 * back to specific draft indices would be impractical/impossible.364 *365 * **Primitive operations** return the native result directly:366 * - `indexOf`, `includes`, `some`, `every`, `join`, etc.367 *368 * @param state - The proxy array state369 * @param method - The non-mutating method name370 * @param args - Arguments passed to the method371 * @returns Drafts for subset operations, base values for transforms, primitives otherwise372 */373 function handleNonMutatingOperation(374 state: ProxyArrayState,375 method: NonMutatingArrayMethod,376 args: any[]377 ) {378 const source = latest(state)379380 // Methods that return arrays with selected items - need to return drafts381 if (method === "filter") {382 const predicate = args[0]383 const result: any[] = []384385 // First pass: call predicate on base values to determine which items pass386 for (let i = 0; i < source.length; i++) {387 if (predicate(source[i], i, source)) {388 // Only create draft for items that passed the predicate389 result.push(state.draft_[i])390 }391 }392393 return result394 }395396 if (FIND_METHODS.has(method)) {397 const predicate = args[0]398 const isForward = method === "find"399 const step = isForward ? 1 : -1400 const start = isForward ? 0 : source.length - 1401402 for (let i = start; i >= 0 && i < source.length; i += step) {403 if (predicate(source[i], i, source)) {404 return state.draft_[i]405 }406 }407 return undefined408 }409410 if (method === "slice") {411 const rawStart = args[0] ?? 0412 const rawEnd = args[1] ?? source.length413414 // Normalize negative indices415 const start = normalizeSliceIndex(rawStart, source.length)416 const end = normalizeSliceIndex(rawEnd, source.length)417418 const result: any[] = []419420 // Return drafts for items in the slice range421 for (let i = start; i < end; i++) {422 result.push(state.draft_[i])423 }424425 return result426 }427428 // For other methods, call on base array directly:429 // - indexOf, includes, join, toString: Return primitives, no draft needed430 // - concat, flat: Return NEW arrays (not subsets). Elements are base values.431 // This is intentional - concat/flat create new data structures rather than432 // selecting subsets of the original, making draft tracking impractical.433 return source[method as keyof typeof Array.prototype](...args)434 }435436 loadPlugin(PluginArrayMethods, {437 createMethodInterceptor,438 isArrayOperationMethod,439 isMutatingArrayMethod440 })441}