#2692
Medium JavaScript Make object immutable
62.1% acceptance
Mar 31, 2026
17
1
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.
Solution
TypeScript
Time O(1)
Space O(1)
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
type Obj = Array<JSONValue> | Record<string, JSONValue>;
function makeImmutable(obj: Obj): Obj {
const mutatingMethods = ['pop', 'push', 'shift', 'unshift', 'splice', 'sort', 'reverse'];
const handler: ProxyHandler<any> = {
set(_target, prop) {
if (Array.isArray(_target)) {
throw `Error Modifying Index: ${String(prop)}`;
}
throw `Error Modifying: ${String(prop)}`;
},
get(target, prop) {
if (Array.isArray(target) && mutatingMethods.includes(String(prop))) {
return () => { throw `Error Calling Method: ${String(prop)}`; };
}
const value = target[prop];
if (value !== null && typeof value === 'object') {
return new Proxy(value, handler);
}
return value;
}
};
return new Proxy(obj, handler);
};
/**
* const obj = makeImmutable({x: 5});
* obj.x = 6; // throws "Error Modifying x"
*/