Skip to content
Myr

arrayMethods.ts

This file

Path

src/plugins/arrayMethods.ts

440 lines · 13.3 KiB · TypeScript

Last changed by

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

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		markChanged(state)178		if (markLength) state.assigned_!.set("length", true)179		return result180	}181182	function markAllIndicesReassigned(state: ProxyArrayState) {183		state.allIndicesReassigned_ = true184	}185186	function normalizeSliceIndex(index: number, length: number): number {187		if (index < 0) {188			return Math.max(length + index, 0)189		}190		return Math.min(index, length)191	}192193	/**194	 * Calls handleCrossReference for each value being inserted into the array,195	 * and marks the corresponding indices as assigned in `assigned_`.196	 *197	 * This ensures nested drafts inside inserted values (e.g. from spreading198	 * a draft object) are properly finalized, matching the behavior of the199	 * proxy set trap which calls handleCrossReference on every assignment.200	 *201	 * Without this, values containing draft proxies (like `{...state[0]}`)202	 * pushed via the array methods plugin would have their nested drafts203	 * revoked during finalization without being replaced by final values.204	 */205	function handleInsertedValues(206		state: ProxyArrayState,207		startIndex: number,208		values: any[]209	) {210		for (let i = 0; i < values.length; i++) {211			const index = startIndex + i212			state.assigned_!.set(index, true)213			handleCrossReference(state, index, values[i])214		}215	}216217	/**218	 * Handles mutating operations that add/remove elements (push, pop, shift, unshift, splice).219	 *220	 * Operates directly on `state.copy_` without creating per-element proxies.221	 * For shifting methods (shift, unshift), marks all indices as reassigned since222	 * indices shift.223	 *224	 * @returns For push/pop/shift/unshift: the native method result. For others: the draft.225	 */226	function handleSimpleOperation(227		state: ProxyArrayState,228		method: string,229		args: any[]230	) {231		return executeArrayMethod(state, () => {232			// For push/unshift, capture the length before the operation233			// so we can compute insertion indices for handleCrossReference234			const lengthBefore = state.copy_!.length235236			const result = (state.copy_! as any)[method](...args)237238			// Handle index reassignment for shifting methods239			if (SHIFTING_METHODS.has(method as MutatingArrayMethod)) {240				markAllIndicesReassigned(state)241			}242243			// Handle cross-references for newly inserted values.244			// push appends at the end, unshift inserts at the beginning.245			if (method === "push" && args.length > 0) {246				handleInsertedValues(state, lengthBefore, args)247			} else if (method === "unshift" && args.length > 0) {248				handleInsertedValues(state, 0, args)249			}250251			// Return appropriate value based on method252			return RESULT_RETURNING_METHODS.has(method as MutatingArrayMethod)253				? result254				: state.draft_255		})256	}257258	/**259	 * Handles reordering operations (reverse, sort) that change element order.260	 *261	 * Operates directly on `state.copy_` and marks all indices as reassigned262	 * since element positions change. Does not mark length as changed since263	 * these operations preserve array length.264	 *265	 * @returns The draft proxy for method chaining.266	 */267	function handleReorderingOperation(268		state: ProxyArrayState,269		method: string,270		args: any[]271	) {272		return executeArrayMethod(273			state,274			() => {275				;(state.copy_! as any)[method](...args)276				markAllIndicesReassigned(state)277				return state.draft_278			},279			false280		) // Don't mark length as changed281	}282283	/**284	 * Creates an interceptor function for a specific array method.285	 *286	 * The interceptor wraps array method calls to:287	 * 1. Set `state.operationMethod` flag during execution (allows proxy `get` trap288	 *    to detect we're inside an optimized method and skip proxy creation)289	 * 2. Route to appropriate handler based on method type290	 * 3. Clean up the operation flag in `finally` block291	 *292	 * The `operationMethod` flag is the key mechanism that enables the proxy's `get`293	 * trap to return base values instead of creating nested proxies during iteration.294	 *295	 * @param state - The proxy array state296	 * @param originalMethod - Name of the array method being intercepted297	 * @returns Interceptor function that handles the method call298	 */299	function createMethodInterceptor(300		state: ProxyArrayState,301		originalMethod: string302	) {303		return function interceptedMethod(...args: any[]) {304			// Enter operation mode - this flag tells the proxy's get trap to return305			// base values instead of creating nested proxies during iteration306			const method = originalMethod as ArrayOperationMethod307			enterOperation(state, method)308309			try {310				// Check if this is a mutating method311				if (isMutatingArrayMethod(method)) {312					// Direct method dispatch - no configuration lookup needed313					if (RESULT_RETURNING_METHODS.has(method)) {314						return handleSimpleOperation(state, method, args)315					}316					if (REORDERING_METHODS.has(method)) {317						return handleReorderingOperation(state, method, args)318					}319320					if (method === "splice") {321						const res = executeArrayMethod(state, () =>322							state.copy_!.splice(...(args as [number, number, ...any[]]))323						)324						markAllIndicesReassigned(state)325						// Handle cross-references for inserted values (args from index 2+)326						if (args.length > 2) {327							const startIndex = normalizeSliceIndex(328								args[0] ?? 0,329								state.copy_!.length330							)331							handleInsertedValues(state, startIndex, args.slice(2))332						}333						return res334					}335				} else {336					// Handle non-mutating methods337					return handleNonMutatingOperation(state, method, args)338				}339			} finally {340				// Always exit operation mode - must be in finally to handle exceptions341				exitOperation(state)342			}343		}344	}345346	/**347	 * Handles non-mutating array methods with different return semantics.348	 *349	 * **Subset operations** return draft proxies for mutation tracking:350	 * - `filter`, `slice`: Return `state.draft_[i]` for each selected element351	 * - `find`, `findLast`: Return `state.draft_[i]` for the found element352	 *353	 * This allows mutations on returned elements to propagate back to the draft:354	 * ```ts355	 * const filtered = draft.items.filter(x => x.value > 5)356	 * filtered[0].value = 999 // Mutates draft.items[originalIndex]357	 * ```358	 *359	 * **Transform operations** return base values (no draft tracking):360	 * - `concat`, `flat`: These create NEW arrays rather than selecting subsets.361	 *   Since the result structure differs from the original, tracking mutations362	 *   back to specific draft indices would be impractical/impossible.363	 *364	 * **Primitive operations** return the native result directly:365	 * - `indexOf`, `includes`, `some`, `every`, `join`, etc.366	 *367	 * @param state - The proxy array state368	 * @param method - The non-mutating method name369	 * @param args - Arguments passed to the method370	 * @returns Drafts for subset operations, base values for transforms, primitives otherwise371	 */372	function handleNonMutatingOperation(373		state: ProxyArrayState,374		method: NonMutatingArrayMethod,375		args: any[]376	) {377		const source = latest(state)378379		// Methods that return arrays with selected items - need to return drafts380		if (method === "filter") {381			const predicate = args[0]382			const result: any[] = []383384			// First pass: call predicate on base values to determine which items pass385			for (let i = 0; i < source.length; i++) {386				if (predicate(source[i], i, source)) {387					// Only create draft for items that passed the predicate388					result.push(state.draft_[i])389				}390			}391392			return result393		}394395		if (FIND_METHODS.has(method)) {396			const predicate = args[0]397			const isForward = method === "find"398			const step = isForward ? 1 : -1399			const start = isForward ? 0 : source.length - 1400401			for (let i = start; i >= 0 && i < source.length; i += step) {402				if (predicate(source[i], i, source)) {403					return state.draft_[i]404				}405			}406			return undefined407		}408409		if (method === "slice") {410			const rawStart = args[0] ?? 0411			const rawEnd = args[1] ?? source.length412413			// Normalize negative indices414			const start = normalizeSliceIndex(rawStart, source.length)415			const end = normalizeSliceIndex(rawEnd, source.length)416417			const result: any[] = []418419			// Return drafts for items in the slice range420			for (let i = start; i < end; i++) {421				result.push(state.draft_[i])422			}423424			return result425		}426427		// For other methods, call on base array directly:428		// - indexOf, includes, join, toString: Return primitives, no draft needed429		// - concat, flat: Return NEW arrays (not subsets). Elements are base values.430		//   This is intentional - concat/flat create new data structures rather than431		//   selecting subsets of the original, making draft tracking impractical.432		return source[method as keyof typeof Array.prototype](...args)433	}434435	loadPlugin(PluginArrayMethods, {436		createMethodInterceptor,437		isArrayOperationMethod,438		isMutatingArrayMethod439	})440}