Skip to content

Instantly share code, notes, and snippets.

@nzakas

nzakas/arrayproxy.js

Created Feb 16, 2016
Embed
What would you like to do?
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