Created
June 27, 2023 03:23
-
-
Save kevinbarabash/38d5ed0ca462ef62604a3aa826692859 to your computer and use it in GitHub Desktop.
Proxied Array to enabled negative indices on arrays in JavaScript
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
const arrayInstanceHandler = { | |
get(target, property, receiver) { | |
if (property < 0) { | |
property = target.length + parseInt(property); | |
} | |
return target[property]; | |
}, | |
}; | |
const arrayConstructorHandler = { | |
construct(target, args) { | |
return new Proxy(new target(...args), arrayInstanceHandler); | |
}, | |
}; | |
const ProxiedArray = new Proxy(Array, arrayConstructorHandler); | |
const arr1 = new ProxiedArray(1, 2, 3); | |
const last = arr1[-1]; | |
console.log("last = ", last); // 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment