Created
May 31, 2024 11:22
-
-
Save jonrandy/ad0c507d66498fb2f06964928c2db11e to your computer and use it in GitHub Desktop.
Proxy an Array to allow negative indexes (like Array.at)
This file contains 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 arr = [1, 2, 3, 4] | |
const handler = { | |
get(target, prop, receiver) { | |
// try to convert property to a number | |
const n = +prop | |
// if it's a number less than zero, return the correct item from the array | |
if (!isNaN(n) && n<0) { | |
return Reflect.get(target, target.length + n, receiver) | |
// otherwise continue as normal with the property | |
} else { | |
return Reflect.get(...arguments) | |
} | |
} | |
} | |
const myArr = new Proxy(arr, handler) | |
console.log(myArr[0]) // 1 | |
console.log(myArr[2]) // 3 | |
console.log(myArr[-1]) // 4 | |
console.log(myArr[-3]) // 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment