Skip to content

Instantly share code, notes, and snippets.

@jonrandy
Created May 31, 2024 11:22
Show Gist options
  • Save jonrandy/ad0c507d66498fb2f06964928c2db11e to your computer and use it in GitHub Desktop.
Save jonrandy/ad0c507d66498fb2f06964928c2db11e to your computer and use it in GitHub Desktop.
Proxy an Array to allow negative indexes (like Array.at)
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