Last active
April 26, 2024 20:04
-
-
Save fitzgen/474256f6baf384a8cbe1 to your computer and use it in GitHub Desktop.
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
"use strict"; | |
var immut = (function () { | |
var descriptor = { | |
value: null | |
}; | |
return function immut() { | |
if (arguments.length % 2 !== 0) | |
throw new Error('Requires an even number of arguments!'); | |
var obj = {}; | |
for (var i = 0, len = arguments.length; i < len; i += 2) { | |
descriptor.value = arguments[i + 1]; | |
Object.defineProperty(obj, arguments[i], descriptor); | |
} | |
descriptor.value = null; | |
Object.preventExtensions(obj); | |
return obj; | |
}; | |
}()); |
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
"use strict"; | |
let immut = (function () { | |
let descriptor = { | |
value: null | |
}; | |
return (...args) => { | |
if (args.length % 2 !== 0) | |
throw new Error('Requires an even number of arguments!'); | |
let obj = {}; | |
for (let i = 0, len = args.length; i < len; i += 2) { | |
descriptor.value = args[i + 1]; | |
Object.defineProperty(obj, args[i], descriptor); | |
} | |
descriptor.value = null; | |
Object.preventExtensions(obj); | |
return obj; | |
}; | |
}()); | |
// Usage: | |
// | |
// let a = immut("foo", 1, | |
// "bar", 2); | |
// | |
// a.baz = 3; // Error: a is not extensible | |
// a.foo = 4; // Error: "foo" is read-only |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment