Skip to content

Instantly share code, notes, and snippets.

@nzakas
Created February 16, 2016 20:46
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nzakas/3ba5a79ab49756939fc3 to your computer and use it in GitHub Desktop.
Save nzakas/3ba5a79ab49756939fc3 to your computer and use it in GitHub Desktop.
A proxy that acts like an array
// target is the backing object
let target = { length: 0 },
proxy = new Proxy(target, {
set(trapTarget, key, value) {
let numericKey = Number(key),
keyIsInteger = Number.isInteger(numericKey);
// special case for length property - only need to worry if length is
// shorter than number of array items
if (key === "length" && value < trapTarget.length) {
// delete everything after the new length
for (let index = trapTarget.length; index >= value; index--) {
Reflect.deleteProperty(trapTarget, index);
}
} else if (keyIsInteger && numericKey >= trapTarget.length) {
// update length if the key is numerically greater than the array length
Reflect.set(trapTarget, "length", numericKey + 1);
}
// assign the property as normal
Reflect.set(trapTarget, key, value);
}
});
console.log(proxy.length); // 0
proxy[0] = "proxy1";
console.log(proxy.length); // 1
proxy[1] = "proxy2";
console.log(proxy.length); // 2
proxy.length = 0;
console.log(proxy.length); // 0
console.log(proxy[0]); // undefined
console.log(0 in proxy); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment