Skip to content

Instantly share code, notes, and snippets.

@mgtitimoli
Last active June 29, 2016 15:53
Show Gist options
  • Save mgtitimoli/e25904f18e271bb7379018951e6e125c to your computer and use it in GitHub Desktop.
Save mgtitimoli/e25904f18e271bb7379018951e6e125c to your computer and use it in GitHub Desktop.
Add multiple descriptors with numeric keys
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);
}
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