Approach
Depth-first search
For Make Object Immutable, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 50 lines of TypeScript from the credited upstream file 2692.ts.
- The implementation visibly relies on ordered lookup.
- No explicit loop blocks detected.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1type RecursiveHandler = {2 set: <T extends object>(target: T, prop: string, value: any) => boolean;3 get: <T extends object>(target: T, prop: string) => any;4 apply: <T extends Function>(target: T, thisArg: any, argArray?: any) => any;5};6 7function makeImmutable<T extends object | Function>(obj: T): T {8 9 const methods = new Set([10 'pop',11 'push',12 'shift',13 'unshift',14 'splice',15 'sort',16 'reverse',17 ]);18 19 const handler: RecursiveHandler = {20 21 set(target, prop, _) {22 throw Array.isArray(target)23 ? `Error Modifying Index: ${String(prop)}`24 : `Error Modifying: ${String(prop)}`;25 },26 27 28 get(target, prop) {29 30 31 32 33 const key = prop as keyof typeof target;34 return prop === 'prototype' ||35 target[key] === null ||36 (typeof target[key] !== 'object' && typeof target[key] !== 'function')37 ? target[key]38 : new Proxy(target[key], this);39 },40 41 apply(target, thisArg, argumentsList) {42 if (methods.has((target as any).name))43 throw `Error Calling Method: ${(target as any).name}`;44 return target.apply(thisArg, argumentsList);45 },46 };47 48 return new Proxy(obj, handler) as T;49}50