Last active
June 29, 2016 15:53
-
-
Save mgtitimoli/e25904f18e271bb7379018951e6e125c to your computer and use it in GitHub Desktop.
Add multiple descriptors with numeric keys
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
function createDescriptor(key) { | |
return { | |
enumerable: true, | |
get() { | |
// do some stuff | |
return this.data[key]; | |
}, | |
set(value) { | |
// do some stuff | |
this.data[key] = value; | |
} | |
}; | |
} | |
function getDescriptors(from, amount) { | |
const descriptors = getDescriptors.cache.slice(from, amount); | |
const missing = amount - descriptors.length; | |
if (missing > 0) { | |
const newDescriptors = Array | |
.apply(null, {length: missing}) | |
.map((undef, index) => createDescriptor(from + index)); | |
getDescriptors.cache.push(...newDescriptors); | |
descriptors.push(...newDescriptors); | |
} | |
return descriptors; | |
} | |
getDescriptors.cache = []; | |
function addProperties(arrayLikeObj, from, amount) { | |
const descriptorsToAdd = Array(from).concat(getDescriptors(from, amount)); | |
Object.defineProperties(arrayLikeObj, descriptorsToAdd); | |
} |
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
var obj = {}; | |
var from = 30; | |
var amount = 40; | |
var propDesc = { | |
configurable: false, | |
writable: true, | |
enumerable: true, | |
value: 300 | |
}; | |
var allPropDescs = Array(from + amount + 1).fill(propDesc, from); | |
Object.defineProperties(obj, allPropDescs); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment