Last active
July 13, 2019 20:11
-
-
Save monkeymonk/0aa9c019caae75294d796084d4026237 to your computer and use it in GitHub Desktop.
Define unwritable property to the given object.
This file contains 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
/** | |
* Define unwritable property to the given object. | |
* @example | |
* var test = {}; | |
* test = definePropertyFreeze(test, 'foo', 'bar'); | |
* test = definePropertyFreeze(test, 'baz', {bat: 'bral'}); | |
* test = definePropertyFreeze(test, 'bot', [1, 2]); | |
* // then | |
* test.bat = 'ok'; // works | |
* test.foo = 'nok'; // not working, test.foo return 'bar' | |
* test.baz.ouch = 'nok'; // not working, test.baz return {bat: "bral"} | |
* test.baz.bat = 'nok'; // not working, test.baz.bat return "bral" | |
* test.bot.push(3); // not working, test.bot returns [1, 2] | |
*/ | |
export default function definePropertyFreeze(obj, name, value) { | |
if (Array.isArray(value) || typeof value === 'object' && value.constructor === Object) { | |
const context = Array.isArray(value) ? [] : {}; | |
value = Object.entries(value).reduce((acc, [k, v]) => { | |
acc[k] = definePropertyFreeze(acc, k, v); | |
return acc; | |
}, context); | |
value = Object.freeze(value); | |
} | |
Object.defineProperty(obj, name, { | |
configurable: true, | |
enumerable: true, | |
value: value, | |
writable: false, | |
}); | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment