Update deepFreeze.md
This commit is contained in:
@ -5,13 +5,17 @@ tags: object,recursion,intermediate
|
|||||||
|
|
||||||
Deep freezes an object.
|
Deep freezes an object.
|
||||||
|
|
||||||
Calls `Object.freeze(obj)` recursively on all unfrozen properties of passed object that are `instanceof` object.
|
Use `Object.keys()` to get all the properties of the passed object, `Array.prototype.forEach()` to iterate over them.
|
||||||
|
Call `Object.freeze(obj)` recursively on all properties, checking if each one is frozen using `Object.isFrozen()` and applying `deepFreeze()` as necessary.
|
||||||
|
Finally, use `Object.freeze()` to freeze the given object.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const deepFreeze = obj =>
|
const deepFreeze = obj => {
|
||||||
Object.keys(obj).forEach(prop =>
|
Object.keys(obj).forEach(prop =>
|
||||||
!(obj[prop] instanceof Object) || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop])
|
obj[prop] = typeof obj[prop] === 'object' && !Object.isFrozen(obj[prop]) ? deepFreeze(obj[prop]) : obj[prop]
|
||||||
) || Object.freeze(obj);
|
);
|
||||||
|
return Object.freeze(obj);
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@ -21,4 +25,4 @@ const o = deepFreeze([1, [2, 3]]);
|
|||||||
|
|
||||||
o[0] = 3; // not allowed
|
o[0] = 3; // not allowed
|
||||||
o[1][0] = 4; // not allowed as well
|
o[1][0] = 4; // not allowed as well
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user