Immutability Helper - Problem
Creating clones of immutable objects with minor alterations can be a tedious process. Write a class ImmutableHelper that serves as a tool to help with this requirement.
The constructor accepts an immutable object obj which will be a JSON object or array. The class has a single method produce which accepts a function mutator. The function returns a new object which is similar to the original except it has those mutations applied.
mutator accepts a proxied version of obj. A user of this function can (appear to) mutate this object, but the original object obj should not actually be affected.
Example usage:
const originalObj = {"x": 5};
const helper = new ImmutableHelper(originalObj);
const newObj = helper.produce((proxy) => {
proxy.x = proxy.x + 1;
});
console.log(originalObj); // {"x": 5}
console.log(newObj); // {"x": 6}Properties of the mutator function:
- It will always return undefined
- It will never access keys that don't exist
- It will never delete keys (delete obj.key)
- It will never call methods on a proxied object (push, shift, etc)
- It will never set keys to objects (proxy.x = {})
Input & Output
Example 1 — Basic Property Modification
$
Input:
obj = {"x": 5}, mutator = "proxy.x = proxy.x + 1"
›
Output:
{"x": 6}
💡 Note:
The mutator increments the x property from 5 to 6. Original object remains {"x": 5}, new object becomes {"x": 6}
Example 2 — Multiple Properties
$
Input:
obj = {"a": 1, "b": 2}, mutator = "proxy.a = 10; proxy.b = 20"
›
Output:
{"a": 10, "b": 20}
💡 Note:
Both properties are modified: a changes from 1 to 10, b changes from 2 to 20
Example 3 — Array Modification
$
Input:
obj = [1, 2, 3], mutator = "proxy[0] = 99"
›
Output:
[99, 2, 3]
💡 Note:
First element of array changes from 1 to 99, other elements remain unchanged
Constraints
- obj will be a valid JSON object or array
- mutator will only perform allowed operations
- mutator will not access non-existent keys
- mutator will not delete properties
- mutator will not assign objects as values
Visualization
Tap to expand
Understanding the Visualization
1
Input
Original object {x: 5} and mutation function
2
Process
Apply mutations through proxy without affecting original
3
Output
New object {x: 6} while original stays {x: 5}
Key Takeaway
🎯 Key Insight: Use Proxy to intercept mutations and apply them to copies, enabling immutable-style programming
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code