Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Last active January 11, 2023 05:16
Show Gist options
  • Save jonathantneal/c88ffbdcb877d98a653a6d81df1d298c to your computer and use it in GitHub Desktop.
Save jonathantneal/c88ffbdcb877d98a653a6d81df1d298c to your computer and use it in GitHub Desktop.
defineProp: Like Object.defineProperty but with a bitmask number instead of a complex object
/*
| bitmask | enumerable | configurable | writable | accessor |
| ------- | ---------- | ------------ | -------- | -------- |
| 0 | | | | |
| 1 | YES | | | |
| 2 | | YES | | |
| 3 | YES | YES | | |
| 4 | | | YES | |
| 5 | YES | | YES | |
| 6 | | YES | YES | |
| 7 | YES | YES | YES | |
| 8 | | | | YES |
| 9 | YES | | | YES |
| 10 | | YES | | YES |
| 11 | YES | YES | | YES |
*/
function defineProp(object, name, bitmask, valueOrGetter, setter) {
var descriptor = { configurable: bitmask & 2, enumerable: bitmask & 1 }
if (bitmask & 4) descriptor.writable = true
if (bitmask & 8) {
descriptor.get = valueOrGetter
descriptor.set = setter
} else descriptor.value = valueOrGetter
return Object.defineProperty(object, name, descriptor)
}
/* Example Usage:
defineProp({}, "arf", 2, "configurable value")
defineProp({}, "boo", 6, "configurable & writable value")
defineProp({}, "caw", 7, "configurable & writable & enumerable value") */
function defineProps(object, props) {
for (var name in props) defineProp(object, name, props[name][0], props[name][1])
return object
}
/* Example Usage:
defineProps({}, {
arf: [2, "configurable value"],
boo: [6, "configurable & writable value"],
caw: [7, "configurable & writable & enumerable value"]
}) */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment