update deepFreeze

This commit is contained in:
Stefan Feješ
2018-09-01 12:01:02 +02:00
parent 87552862c3
commit 21632f87b6
2 changed files with 1567 additions and 1581 deletions

View File

@ -2,37 +2,23 @@
Deep freezes an object.
Calls `Object.freeze(obj)` recursively on all unfrozen properties of obj that are `typeof` function or object.
Calls `Object.freeze(obj)` recursively on all unfrozen properties of passed object that are `instanceof` object.
```js
const deepFreeze = obj => {
Object.freeze(obj);
Object.getOwnPropertyNames(obj).forEach(function(prop) {
if (
obj.hasOwnProperty(prop) &&
obj[prop] !== null &&
(typeof obj[prop] === 'object' || typeof obj[prop] === 'function') &&
!Object.isFrozen(obj[prop])
) {
deepFreeze(obj[prop]);
}
});
return obj;
};
const deepFreeze = obj =>
Object.keys(obj).forEach(
prop =>
!obj[prop] instanceof Object || Object.isFrozen(obj[prop])
? null
: deepFreeze(obj[prop])
) || Object.freeze(obj);
```
```js
'use strict';
const a = Object.freeze([1, [2, 3]]);
const o = deepFreeze([1, [2, 3]]);
a[0] = 3; // not allowed
a[1][0] = 4; // allowed but shouldn't be
const b = deepFreeze([1, [2, 3]]);
b[0] = 3; // not allowed
b[1][0] = 4; // not allowed as well
o[0] = 3; // not allowed
o[1][0] = 4; // not allowed as well
```