-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdeepFreeze.js
36 lines (29 loc) · 872 Bytes
/
deepFreeze.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function deepFreeze(obj) {
// Freeze the current object
Object.freeze(obj);
// Recursively freeze all properties that are objects
for (const key in obj) {
if (typeof obj[key] === "object" && obj[key] !== null) {
deepFreeze(obj[key]);
}
}
return obj;
}
// Example usage
const config = {
api: {
url: "https://api.example.com",
timeout: 5000,
},
settings: {
theme: "dark",
notifications: true,
},
};
deepFreeze(config);
// Trying to modify any property (will fail)
config.api.timeout = 7000; // ❌ Error: Cannot assign to read-only property
// Trying to add a new property (will fail)
config.settings.newProperty = "test"; // ❌ Error: Cannot add property
// Trying to delete a property (will fail)
delete config.settings.theme; // ❌ Error: Cannot delete property