Skip to content
Myr

arrayMethods.ts

This file

Path

src/plugins/arrayMethods.ts

510 lines · 16.1 KiB · TypeScript

Last changed by

fix: forward thisArg in the array-methods plugin (#1292)Bao Nguyenbefore adoption1d88550

History of this file

Take it

1import {2	PluginArrayMethods,3	latest,4	loadPlugin,5	markChanged,6	prepareCopy,7	handleCrossReference,8	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()177		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) {190		markChanged(state)191		if (markLength) state.assigned_!.set("length", true)192	}193194	function markAllIndicesReassigned(state: ProxyArrayState) {195		state.allIndicesReassigned_ = true196		state.baseRefs_ = new Set(state.base_)197	}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	/**207	 * 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.217	 *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.222	 */223	function handleInsertedValues(224		state: ProxyArrayState,225		startIndex: number,226		values: any[]227	) {228		for (let i = 0; i < values.length; i++) {229			const index = "" + (startIndex + i)230			state.assigned_!.set(index, true)231			handleCrossReference(state, index, values[i])232		}233	}234235	/**236	 * 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	) {249		// 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		}260261		prepareCopy(state)262263		// For push/unshift, capture the length before the operation264		// so we can compute insertion indices for handleCrossReference265		const lengthBefore = state.copy_!.length266267		const result = (state.copy_! as any)[method](...args)268269		markArrayChanged(state)270271		// Handle index reassignment for shifting methods272		if (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {273			markAllIndicesReassigned(state)274		}275276		// 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)282		}283284		// Return appropriate value based on method285		return RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)286			? result287			: state.draft_288	}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		// Reordering an array with fewer than two elements cannot change it,305		// so preserve structural sharing and skip copying (see306		// handleSimpleOperation for why this must run before prepareCopy).307		if (latest(state).length <= 1) return state.draft_308309		return executeArrayMethod(310			state,311			() => {312				;(state.copy_! as any)[method](...args)313				markAllIndicesReassigned(state)314				return state.draft_315			},316			false317		) // Don't mark length as changed318	}319320	/**321	 * Creates an interceptor function for a specific array method.322	 *323	 * The interceptor wraps array method calls to:324	 * 1. Set `state.operationMethod` flag during execution (allows proxy `get` trap325	 *    to detect we're inside an optimized method and skip proxy creation)326	 * 2. Route to appropriate handler based on method type327	 * 3. Clean up the operation flag in `finally` block328	 *329	 * The `operationMethod` flag is the key mechanism that enables the proxy's `get`330	 * trap to return base values instead of creating nested proxies during iteration.331	 *332	 * @param state - The proxy array state333	 * @param originalMethod - Name of the array method being intercepted334	 * @returns Interceptor function that handles the method call335	 */336	function createMethodInterceptor(337		state: ProxyArrayState,338		originalMethod: string339	) {340		return function interceptedMethod(...args: any[]) {341			// Enter operation mode - this flag tells the proxy's get trap to return342			// base values instead of creating nested proxies during iteration343			const method = originalMethod as ArrayOperationMethod344			enterOperation(state, method)345346			try {347				// Check if this is a mutating method348				if (isMutatingArrayMethod(method)) {349					// Direct method dispatch - no configuration lookup needed350					if (RESULT_RETURNING_METHODS.has(method)) {351						return handleSimpleOperation(state, method, args)352					}353					if (REORDERING_METHODS.has(method)) {354						return handleReorderingOperation(state, method, args)355					}356357					if (method === "splice") {358						const insertCount = args.length > 2 ? args.length - 2 : 0359360						// Detect no-op calls before creating a copy so structural361						// sharing is preserved (see handleSimpleOperation). A splice362						// removes nothing when called with no arguments, when the363						// normalized start is at/past the end, or when the delete364						// count coerces to less than 1. splice(start) with a single365						// argument removes everything from start onwards, so it must366						// not match. Exotic arguments that slip through are caught367						// by the post-copy check below.368						if (insertCount === 0) {369							const length = latest(state).length370							if (371								args.length === 0 ||372								normalizeSliceIndex(args[0] ?? 0, length) === length ||373								(args.length > 1 && !(args[1] >= 1))374							) {375								return []376							}377						}378379						prepareCopy(state)380						const res = state.copy_!.splice(381							...(args as [number, number, ...any[]])382						)383384						// Backstop for exotic arguments the pre-check above missed:385						// if nothing was removed and nothing inserted, the array is386						// unchanged and must not be marked as modified.387						if (res.length === 0 && insertCount === 0) {388							return res389						}390391						markArrayChanged(state)392						markAllIndicesReassigned(state)393						// Handle cross-references for inserted values (args from index 2+)394						if (insertCount > 0) {395							const startIndex = normalizeSliceIndex(396								args[0] ?? 0,397								state.copy_!.length398							)399							handleInsertedValues(state, startIndex, args.slice(2))400						}401						return res402					}403				} else {404					// Handle non-mutating methods405					return handleNonMutatingOperation(state, method, args)406				}407			} finally {408				// Always exit operation mode - must be in finally to handle exceptions409				exitOperation(state)410			}411		}412	}413414	/**415	 * Handles non-mutating array methods with different return semantics.416	 *417	 * **Subset operations** return draft proxies for mutation tracking:418	 * - `filter`, `slice`: Return `state.draft_[i]` for each selected element419	 * - `find`, `findLast`: Return `state.draft_[i]` for the found element420	 *421	 * This allows mutations on returned elements to propagate back to the draft:422	 * ```ts423	 * const filtered = draft.items.filter(x => x.value > 5)424	 * filtered[0].value = 999 // Mutates draft.items[originalIndex]425	 * ```426	 *427	 * **Transform operations** return base values (no draft tracking):428	 * - `concat`, `flat`: These create NEW arrays rather than selecting subsets.429	 *   Since the result structure differs from the original, tracking mutations430	 *   back to specific draft indices would be impractical/impossible.431	 *432	 * **Primitive operations** return the native result directly:433	 * - `indexOf`, `includes`, `some`, `every`, `join`, etc.434	 *435	 * @param state - The proxy array state436	 * @param method - The non-mutating method name437	 * @param args - Arguments passed to the method438	 * @returns Drafts for subset operations, base values for transforms, primitives otherwise439	 */440	function handleNonMutatingOperation(441		state: ProxyArrayState,442		method: NonMutatingArrayMethod,443		args: any[]444	) {445		const source = latest(state)446447		// Methods that return arrays with selected items - need to return drafts448		if (method === "filter") {449			const predicate = args[0]450			const thisArg = args[1]451			const result: any[] = []452453			// First pass: call predicate on base values to determine which items pass454			for (let i = 0; i < source.length; i++) {455				if (predicate.call(thisArg, source[i], i, source)) {456					// Only create draft for items that passed the predicate457					result.push(state.draft_[i])458				}459			}460461			return result462		}463464		if (FIND_METHODS.has(method)) {465			const predicate = args[0]466			const thisArg = args[1]467			const isForward = method === "find"468			const step = isForward ? 1 : -1469			const start = isForward ? 0 : source.length - 1470471			for (let i = start; i >= 0 && i < source.length; i += step) {472				if (predicate.call(thisArg, source[i], i, source)) {473					return state.draft_[i]474				}475			}476			return undefined477		}478479		if (method === "slice") {480			const rawStart = args[0] ?? 0481			const rawEnd = args[1] ?? source.length482483			// Normalize negative indices484			const start = normalizeSliceIndex(rawStart, source.length)485			const end = normalizeSliceIndex(rawEnd, source.length)486487			const result: any[] = []488489			// Return drafts for items in the slice range490			for (let i = start; i < end; i++) {491				result.push(state.draft_[i])492			}493494			return result495		}496497		// For other methods, call on base array directly:498		// - indexOf, includes, join, toString: Return primitives, no draft needed499		// - concat, flat: Return NEW arrays (not subsets). Elements are base values.500		//   This is intentional - concat/flat create new data structures rather than501		//   selecting subsets of the original, making draft tracking impractical.502		return source[method as keyof typeof Array.prototype](...args)503	}504505	loadPlugin(PluginArrayMethods, {506		createMethodInterceptor,507		isArrayOperationMethod,508		isMutatingArrayMethod509	})510}