Created
September 18, 2016 08:07
-
-
Save sudaraka/e02c899c17949ffbcb8b5b3f17831555 to your computer and use it in GitHub Desktop.
Deep freeze an object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* deep-freeze.js: Deep freeze an object | |
* | |
* Copyright 2016 Sudaraka Wijesinghe <[email protected]> | |
* | |
* 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