Skip to content

Instantly share code, notes, and snippets.

@monkeymonk
Last active July 13, 2019 20:11
Show Gist options
  • Save monkeymonk/0aa9c019caae75294d796084d4026237 to your computer and use it in GitHub Desktop.
Save monkeymonk/0aa9c019caae75294d796084d4026237 to your computer and use it in GitHub Desktop.
Define unwritable property to the given object.
/**
* 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