Problem
Write a function that takes an object obj
and returns a new immutable version of this object.
An **immutable **object is an object that can’t be altered and will throw an error if any attempt is made to alter it.
There are three types of error messages that can be produced from this new object.
- Attempting to modify a key on the object will result in this error message:
Error Modifying: ${key}
. - Attempting to modify an index on an array will result in this error message:
Error Modifying Index: ${index}
. - Attempting to call a method that mutates an array will result in this error message:
Error Calling Method: ${methodName}
. You may assume the only methods that can mutate an array are['pop', 'push', 'shift', 'unshift', 'splice', 'sort', 'reverse']
.
obj
is a valid JSON object or array, meaning it is the output of
JSON.parse()
.
Note that a string literal should be thrown, not an Error
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Example 4:
|
|
Constraints:
obj
is a valid JSON object or array2 <= JSON.stringify(obj).length <= 10^5
Solution
Method 1 – Proxy and Recursion
Intuition
To make an object deeply immutable, we can use JavaScript’s Proxy to intercept all mutation attempts. For objects and arrays, we recursively wrap their properties or elements. For arrays, we also intercept mutating methods and throw the required error messages.
Approach
- Define a set of mutating array methods:
['pop', 'push', 'shift', 'unshift', 'splice', 'sort', 'reverse']
. - Write a recursive function that returns a Proxy for the input object or array.
- In the Proxy handler:
- For
set
(property assignment), throw an error with the appropriate message for objects or arrays. - For
deleteProperty
, throw an error for deletion attempts. - For arrays, intercept mutating method calls and throw an error.
- For property access, recursively wrap nested objects/arrays.
- For
- Return the Proxy-wrapped object.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
, where n is the number of properties/elements, as each is wrapped once. - 🧺 Space complexity:
O(n)
, for the proxies and recursion stack.