Skip to content

Instantly share code, notes, and snippets.

@sudaraka
Created September 18, 2016 08:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sudaraka/e02c899c17949ffbcb8b5b3f17831555 to your computer and use it in GitHub Desktop.
Save sudaraka/e02c899c17949ffbcb8b5b3f17831555 to your computer and use it in GitHub Desktop.
Deep freeze an object
/**
* deep-freeze.js: Deep freeze an object
*
* Copyright 2016 Sudaraka Wijesinghe <sudaraka@sudaraka.org>
*
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it and/or modify
* it under the terms of the BSD 2-clause License. See the LICENSE file for more
* details.
*
*/
export const
// Recursively freeze the given object
freeze = obj => {
const
thingsToFreeze = [ 'object', 'function' ],
fpropsNotToFreeze = [ 'caller', 'callee', 'arguments', 'prototype' ],
isFunction = 'function' === typeof obj
if(
// No need to freeze if already frozen
!Object.isFrozen(obj)
// No need to freeze a `null`
&& null !== obj
// Check if we need to freeze this type of things
&& thingsToFreeze.includes(typeof obj)
) {
Reflect.ownKeys(obj)
// Not prop of function or prop of a function that is not excluded explicitly
.filter(prop => !isFunction || !fpropsNotToFreeze.includes(prop))
.forEach(prop => freeze(obj[prop]))
return Object.freeze(obj)
}
return obj
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment