Files
30-seconds-of-code/snippets/deepFreeze.md
Roni Bar-David 77e605b044 Update deepFreeze.md
fix typo in line 15, and add missing typeof call
2020-07-20 09:56:30 +03:00

755 B

title, tags
title tags
deepFreeze object,recursion,intermediate

Deep freezes an 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 object is frozen using Object.isFrozen() and applying deepFreeze() as necessary. Finally, use Object.freeze() to freeze the given object.

const deepFreeze = obj => {
  Object.keys(obj).forEach(prop => {
    if (typeof(obj[prop]) === 'object' && !Object.isFrozen(obj[prop])) deepFreeze(obj[prop]);
  });
  return Object.freeze(obj);
};
'use strict';

const o = deepFreeze([1, [2, 3]]);

o[0] = 3; // not allowed
o[1][0] = 4; // not allowed as well