Make Object Immutable - 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: A string literal should be thrown, not an Error.

Input & Output

Example 1 — Object Property Modification
$ Input: obj = {"name": "John", "age": 30}
Output: Attempting obj.name = "Jane" throws "Error Modifying: name"
💡 Note: The immutable object prevents property modification and throws the specific error message
Example 2 — Array Index Modification
$ Input: obj = [1, 2, 3]
Output: Attempting obj[0] = 5 throws "Error Modifying Index: 0"
💡 Note: Array index modifications are blocked with index-specific error message
Example 3 — Array Method Call
$ Input: obj = [1, 2, 3]
Output: Attempting obj.push(4) throws "Error Calling Method: push"
💡 Note: Mutating array methods are overridden to throw method-specific errors

Constraints

  • obj is a valid JSON value
  • obj can be an object, array, or primitive value
  • All nested structures must be made immutable
  • Must throw string literals, not Error objects

Visualization

Tap to expand
Make Object ImmutableMutable{name: "John"}Can modify:obj.name = "Jane" ✓Wrap withProxyImmutable{name: "John"}Throws error:Error Modifying: nameThree error types:• Error Modifying: {key}• Error Modifying Index: {index}• Error Calling Method: {method}Result: Protected object with custom error messages
Understanding the Visualization
1
Input
Mutable JavaScript object or array
2
Process
Wrap with protection mechanism
3
Output
Immutable version that throws on modification
Key Takeaway
🎯 Key Insight: Proxy intercepts all operations to provide immutability with custom error messages
Asked in
Google 25 Facebook 20 Microsoft 15
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen