Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Negative Array Index in Javascript

| Comments

If you are from python or ruby school, you shall be familar with negative array index, like a[-1] will return the last element, a[-2] will return the second-to-last element and so on.

In javascript we can make use of negitve indices like:

1
2
3
4
>> negArray = []; negArray[-100] = -100; negArray.length
(number) 0
>> negArray = []; negArray[-100] = -100; negArray.length; negArray[-100]
(number) -100

Let's add some ES6 proxy masala:

1
2
3
4
5
6
7
8
9
10
11
12
13
function negArray(arr) {
  var dup = arr;

  return Proxy.create({
    set: function (proxy, index, value) {
      dup[index] = value;
    },
    get: function (proxy, index) {
        index = parseInt(index);
        return index < 0 ? dup[dummy.length + index] : dup[index];
    }
  });
}

Now:

1
2
3
console.log(negArray(['eat', 'code', 'sleep'])[-1]);

// Would log sleep

Hope this is useful and there might be many other way to implement the same, do let me know your way of doing this! :)

Update 0 : as suggested by Gundersen we can avoid duplication, as per the code below.

1
2
3
4
5
6
7
8
9
10
11
12
function negArray(arr) {
  return Proxy.create({
    set: function (proxy, index, value) {
        index = parseInt(index);
        return index < 0 ? (arr[arr.length + index] = value) : (arr[index] = value);
    },
    get: function (proxy, index) {
        index = parseInt(index);
        return index < 0 ? arr[arr.length + index] : arr[index];
    }
  });
}

Comments