negative-array

Negative array index support `array[-1]` using ES6 Proxy

npm install negative-array
6 downloads in the last week
12 downloads in the last month

negative-array Build Status

Negative array index support array[-1] using ES6 Proxy

JavaScript doesn't natively support the use of a negative index to get items backwards from the end, but with ES6 Proxy it's possible. Take a look at the source to see how simple it is to implement. There's also a short article about it.

var negativeArray = require('negative-array');

// adds negative array index support to any passed array
var unicorn = negativeArray(['pony', 'cake', 'rainbow']);

// get the last item by using an negative index
console.log(unicorn[-1]);
//=> rainbow

// OMG, YES!

Proxies are objects for which the programmer has to define the semantics in JavaScript. The default object semantics are implemented in the JavaScript engine, often written in lower-level languages like C++. Proxies let the programmer define most of the behavior of an object in JavaScript. They are said to provide a meta-programming API.

This should go without saying; don't use in production.

Demo

Install

Download manually or with a package-manager.

$ npm install --save negative-array
$ bower install --save negative-array
$ component install sindresorhus/negative-array

Compatibility

  • Node >=0.8.0 - with the harmony flag: node --harmony
  • Chrome - with the this flag enabled chrome://flags/#enable-javascript-harmony (copy/paste into address-bar)
  • Firefox >=12

License

MIT © Sindre Sorhus

npm loves you