DEV Community


Discussion on: 3 cool things you can do with Python indexing

daksamit profile image
Dominik Aksamit

The article brings me thought about similar solution in javascript.
Of course, there is a serious lack of something like negative indexing (you need access with arr[arr.length -1])
But, proxies come to the rescue!
it's something like a wrapper object for your data give them superpowers. Let me show you a simple example with arrays:

let arr = [4, 6, 3, 2, 1]

const arrProxy = {
  get(target, prop, receiver) {
    if (prop.startsWith('::')) {
      prop = +prop.slice(2)
      if (prop < 0) {
        return target.reverse().filter((n, i) => (i + 1) % prop === 0)
      return target.filter((n, i) => (i + 1) % prop === 0)
    } else if (prop < 0) {
      prop = +prop + target.length
    return Reflect.get(target, prop, receiver)
arr = new Proxy(arr, arrProxy)

console.log(arr['::-2']) // [2, 6]
console.log(arr[-1]) // 1

arrProxy applies an internal method that gives an ability to do more with your objects.
the prop is always a string, so we need to convert it into a number.
Another caveat - In js ':' is the invalid syntax in this case so wrapping '::-2' in quotes as string

More about proxy:

mariamodan profile image
Maria Author

That's a really nice workaround to use slicing and negative indexes in JavaScript! I do wish sometimes that js array would be as neat to work with as python lists haha

daksamit profile image
Dominik Aksamit

Maybe someday :)
Generally, proxies are a really interesting way to enhance javascript objects and arrays and use them in a way we didn't even imagine what is possible :D