Skip to content

Instantly share code, notes, and snippets.

@tdd
Created May 25, 2016 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdd/6f21695bfba161ecdfb2ebdd47f9c122 to your computer and use it in GitHub Desktop.
Save tdd/6f21695bfba161ecdfb2ebdd47f9c122 to your computer and use it in GitHub Desktop.
Negative indices on arrays using ES2015 proxies
function yay(array) {
return new Proxy(array, {
get (target, property, receiver) {
if (property < 0) {
property = target.length + Number(property)
}
return Reflect.get(target, property, receiver)
}
})
}
// Demo use:
const arr = yay(['foo', 'bar', 'baz'])
arr[-1] // => 'baz'
@tdd
Copy link
Author

tdd commented May 25, 2016

As a reminder, Babel won't transpile proxies: they can't be emulated in ES5. But you do have enough native support for this, as of May 25 2016, in Edge 12+, Fx38+, Ch49+, Saf TP, and Node 6.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment