arrayMethods.ts
This file
Path
src/plugins/arrayMethods.ts
395 lines · 11.6 KiB · TypeScript
Last changed by
feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
History of this fileTake it
feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 1–395why, one step back1import {2 PluginArrayMethods,3 latest,4 loadPlugin,5 markChanged,6 prepareCopy,7 ProxyArrayState8} from "../internal"910/**11 * Methods that directly modify the array in place.12 * These operate on the copy without creating per-element proxies:13 * - `push`, `pop`: Add/remove from end14 * - `shift`, `unshift`: Add/remove from start (marks all indices reassigned)15 * - `splice`: Add/remove at arbitrary position (marks all indices reassigned)16 * - `reverse`, `sort`: Reorder elements (marks all indices reassigned)17 */18type MutatingArrayMethod =19 | "push"20 | "pop"21 | "shift"22 | "unshift"23 | "splice"24 | "reverse"25 | "sort"2627/**28 * Methods that read from the array without modifying it.29 * These fall into distinct categories based on return semantics:30 *31 * **Subset operations** (return drafts - mutations propagate):32 * - `filter`, `slice`: Return array of draft proxies33 * - `find`, `findLast`: Return single draft proxy or undefined34 *35 * **Transform operations** (return base values - mutations don't track):36 * - `concat`, `flat`: Create new structures, not subsets of original37 *38 * **Primitive-returning** (no draft needed):39 * - `findIndex`, `findLastIndex`, `indexOf`, `lastIndexOf`: Return numbers40 * - `some`, `every`, `includes`: Return booleans41 * - `join`, `toString`, `toLocaleString`: Return strings42 */43type NonMutatingArrayMethod =44 | "filter"45 | "slice"46 | "concat"47 | "flat"48 | "find"49 | "findIndex"50 | "findLast"51 | "findLastIndex"52 | "some"53 | "every"54 | "indexOf"55 | "lastIndexOf"56 | "includes"57 | "join"58 | "toString"59 | "toLocaleString"6061/** Union of all array operation methods handled by the plugin. */62export type ArrayOperationMethod = MutatingArrayMethod | NonMutatingArrayMethod6364/**65 * Enables optimized array method handling for Immer drafts.66 *67 * This plugin overrides array methods to avoid unnecessary Proxy creation during iteration,68 * significantly improving performance for array-heavy operations.69 *70 * **Mutating methods** (push, pop, shift, unshift, splice, sort, reverse):71 * Operate directly on the copy without creating per-element proxies.72 *73 * **Non-mutating methods** fall into categories:74 * - **Subset operations** (filter, slice, find, findLast): Return draft proxies - mutations track75 * - **Transform operations** (concat, flat): Return base values - mutations don't track76 * - **Primitive-returning** (indexOf, includes, some, every, etc.): Return primitives77 *78 * **Important**: Callbacks for overridden methods receive base values, not drafts.79 * This is the core performance optimization.80 *81 * @example82 * ```ts83 * import { enableArrayMethods, produce } from "immer"84 *85 * enableArrayMethods()86 *87 * const next = produce(state, draft => {88 * // Optimized - no proxy creation per element89 * draft.items.sort((a, b) => a.value - b.value)90 *91 * // filter returns drafts - mutations propagate92 * const filtered = draft.items.filter(x => x.value > 5)93 * filtered[0].value = 999 // Affects draft.items[originalIndex]94 * })95 * ```96 *97 * @see https://immerjs.github.io/immer/array-methods98 */99export function enableArrayMethods() {100 const SHIFTING_METHODS = new Set<MutatingArrayMethod>(["shift", "unshift"])101102 const QUEUE_METHODS = new Set<MutatingArrayMethod>(["push", "pop"])103104 const RESULT_RETURNING_METHODS = new Set<MutatingArrayMethod>([105 ...QUEUE_METHODS,106 ...SHIFTING_METHODS107 ])108109 const REORDERING_METHODS = new Set<MutatingArrayMethod>(["reverse", "sort"])110111 // Optimized method detection using array-based lookup112 const MUTATING_METHODS = new Set<MutatingArrayMethod>([113 ...RESULT_RETURNING_METHODS,114 ...REORDERING_METHODS,115 "splice"116 ])117118 const FIND_METHODS = new Set<NonMutatingArrayMethod>(["find", "findLast"])119120 const NON_MUTATING_METHODS = new Set<NonMutatingArrayMethod>([121 "filter",122 "slice",123 "concat",124 "flat",125 ...FIND_METHODS,126 "findIndex",127 "findLastIndex",128 "some",129 "every",130 "indexOf",131 "lastIndexOf",132 "includes",133 "join",134 "toString",135 "toLocaleString"136 ])137138 // Type guard for method detection139 function isMutatingArrayMethod(140 method: string141 ): method is MutatingArrayMethod {142 return MUTATING_METHODS.has(method as any)143 }144145 function isNonMutatingArrayMethod(146 method: string147 ): method is NonMutatingArrayMethod {148 return NON_MUTATING_METHODS.has(method as any)149 }150151 function isArrayOperationMethod(152 method: string153 ): method is ArrayOperationMethod {154 return isMutatingArrayMethod(method) || isNonMutatingArrayMethod(method)155 }156157 function enterOperation(158 state: ProxyArrayState,159 method: ArrayOperationMethod160 ) {161 state.operationMethod = method162 }163164 function exitOperation(state: ProxyArrayState) {165 state.operationMethod = undefined166 }167168 // Shared utility functions for array method handlers169 function executeArrayMethod<T>(170 state: ProxyArrayState,171 operation: () => T,172 markLength = true173 ): T {174 prepareCopy(state)175 const result = operation()176 markChanged(state)177 if (markLength) state.assigned_!.set("length", true)178 return result179 }180181 function markAllIndicesReassigned(state: ProxyArrayState) {182 state.allIndicesReassigned_ = true183 }184185 function normalizeSliceIndex(index: number, length: number): number {186 if (index < 0) {187 return Math.max(length + index, 0)188 }189 return Math.min(index, length)190 }191192 /**193 * Handles mutating operations that add/remove elements (push, pop, shift, unshift, splice).194 *195 * Operates directly on `state.copy_` without creating per-element proxies.196 * For shifting methods (shift, unshift), marks all indices as reassigned since197 * indices shift.198 *199 * @returns For push/pop/shift/unshift: the native method result. For others: the draft.200 */201 function handleSimpleOperation(202 state: ProxyArrayState,203 method: string,204 args: any[]205 ) {206 return executeArrayMethod(state, () => {207 const result = (state.copy_! as any)[method](...args)208209 // Handle index reassignment for shifting methods210 if (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {211 markAllIndicesReassigned(state)212 }213214 // Return appropriate value based on method215 return RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)216 ? result217 : state.draft_218 })219 }220221 /**222 * Handles reordering operations (reverse, sort) that change element order.223 *224 * Operates directly on `state.copy_` and marks all indices as reassigned225 * since element positions change. Does not mark length as changed since226 * these operations preserve array length.227 *228 * @returns The draft proxy for method chaining.229 */230 function handleReorderingOperation(231 state: ProxyArrayState,232 method: string,233 args: any[]234 ) {235 return executeArrayMethod(236 state,237 () => {238 ;(state.copy_! as any)[method](...args)239 markAllIndicesReassigned(state)240 return state.draft_241 },242 false243 ) // Don't mark length as changed244 }245246 /**247 * Creates an interceptor function for a specific array method.248 *249 * The interceptor wraps array method calls to:250 * 1. Set `state.operationMethod` flag during execution (allows proxy `get` trap251 * to detect we're inside an optimized method and skip proxy creation)252 * 2. Route to appropriate handler based on method type253 * 3. Clean up the operation flag in `finally` block254 *255 * The `operationMethod` flag is the key mechanism that enables the proxy's `get`256 * trap to return base values instead of creating nested proxies during iteration.257 *258 * @param state - The proxy array state259 * @param originalMethod - Name of the array method being intercepted260 * @returns Interceptor function that handles the method call261 */262 function createMethodInterceptor(263 state: ProxyArrayState,264 originalMethod: string265 ) {266 return function interceptedMethod(...args: any[]) {267 // Enter operation mode - this flag tells the proxy's get trap to return268 // base values instead of creating nested proxies during iteration269 const method = originalMethod as ArrayOperationMethod270 enterOperation(state, method)271272 try {273 // Check if this is a mutating method274 if (isMutatingArrayMethod(method)) {275 // Direct method dispatch - no configuration lookup needed276 if (RESULT_RETURNING_METHODS.has(method)) {277 return handleSimpleOperation(state, method, args)278 }279 if (REORDERING_METHODS.has(method)) {280 return handleReorderingOperation(state, method, args)281 }282283 if (method === "splice") {284 const res = executeArrayMethod(state, () =>285 state.copy_!.splice(...(args as [number, number, ...any[]]))286 )287 markAllIndicesReassigned(state)288 return res289 }290 } else {291 // Handle non-mutating methods292 return handleNonMutatingOperation(state, method, args)293 }294 } finally {295 // Always exit operation mode - must be in finally to handle exceptions296 exitOperation(state)297 }298 }299 }300301 /**302 * Handles non-mutating array methods with different return semantics.303 *304 * **Subset operations** return draft proxies for mutation tracking:305 * - `filter`, `slice`: Return `state.draft_[i]` for each selected element306 * - `find`, `findLast`: Return `state.draft_[i]` for the found element307 *308 * This allows mutations on returned elements to propagate back to the draft:309 * ```ts310 * const filtered = draft.items.filter(x => x.value > 5)311 * filtered[0].value = 999 // Mutates draft.items[originalIndex]312 * ```313 *314 * **Transform operations** return base values (no draft tracking):315 * - `concat`, `flat`: These create NEW arrays rather than selecting subsets.316 * Since the result structure differs from the original, tracking mutations317 * back to specific draft indices would be impractical/impossible.318 *319 * **Primitive operations** return the native result directly:320 * - `indexOf`, `includes`, `some`, `every`, `join`, etc.321 *322 * @param state - The proxy array state323 * @param method - The non-mutating method name324 * @param args - Arguments passed to the method325 * @returns Drafts for subset operations, base values for transforms, primitives otherwise326 */327 function handleNonMutatingOperation(328 state: ProxyArrayState,329 method: NonMutatingArrayMethod,330 args: any[]331 ) {332 const source = latest(state)333334 // Methods that return arrays with selected items - need to return drafts335 if (method === "filter") {336 const predicate = args[0]337 const result: any[] = []338339 // First pass: call predicate on base values to determine which items pass340 for (let i = 0; i < source.length; i++) {341 if (predicate(source[i], i, source)) {342 // Only create draft for items that passed the predicate343 result.push(state.draft_[i])344 }345 }346347 return result348 }349350 if (FIND_METHODS.has(method)) {351 const predicate = args[0]352 const isForward = method === "find"353 const step = isForward ? 1 : -1354 const start = isForward ? 0 : source.length - 1355356 for (let i = start; i >= 0 && i < source.length; i += step) {357 if (predicate(source[i], i, source)) {358 return state.draft_[i]359 }360 }361 return undefined362 }363364 if (method === "slice") {365 const rawStart = args[0] ?? 0366 const rawEnd = args[1] ?? source.length367368 // Normalize negative indices369 const start = normalizeSliceIndex(rawStart, source.length)370 const end = normalizeSliceIndex(rawEnd, source.length)371372 const result: any[] = []373374 // Return drafts for items in the slice range375 for (let i = start; i < end; i++) {376 result.push(state.draft_[i])377 }378379 return result380 }381382 // For other methods, call on base array directly:383 // - indexOf, includes, join, toString: Return primitives, no draft needed384 // - concat, flat: Return NEW arrays (not subsets). Elements are base values.385 // This is intentional - concat/flat create new data structures rather than386 // selecting subsets of the original, making draft tracking impractical.387 return source[method as keyof typeof Array.prototype](...args)388 }389390 loadPlugin(PluginArrayMethods, {391 createMethodInterceptor,392 isArrayOperationMethod,393 isMutatingArrayMethod394 })395}