Skip to content

Instantly share code, notes, and snippets.

@monkeymonk
Created October 23, 2019 22:48
Show Gist options
  • Save monkeymonk/be0e6f71b7696fa79bc603db3693a177 to your computer and use it in GitHub Desktop.
Save monkeymonk/be0e6f71b7696fa79bc603db3693a177 to your computer and use it in GitHub Desktop.
freezeRecursive method #javascript #es6
/**
* Freeze given value recursively if needed.
* @param obj
* @return {*}
*/
export default function freezeRecursive(obj) {
Object.freeze(obj);
if (obj === undefined) {
return obj;
}
Object.getOwnPropertyNames(obj).forEach((prop) => {
if (
obj[prop] !== null
&& (typeof obj[prop] === 'object' || typeof obj[prop] === 'function')
&& !Object.isFrozen(obj[prop])
) {
freezeRecursive(obj[prop]);
}
});
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment