Created
February 16, 2016 20:46
-
-
Save nzakas/3ba5a79ab49756939fc3 to your computer and use it in GitHub Desktop.
A proxy that acts like an array
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
// 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