Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Created May 21, 2011 21:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DmitrySoshnikov/984921 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/984921 to your computer and use it in GitHub Desktop.
Manual negative indicies of arrays in ES5
/**
* Manual negative indicies for arrays in ES5:
* usually we use in such cases only first three
* negative indices, so these are enough (you may
* add -4, -5, etc. if needed).
*
* See also the implementation with proxies:
* https://github.com/DmitrySoshnikov/es-laboratory/blob/master/src/array-negative-indices.js
*
* by Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
* MIT Style License
*/
[-1, -2, -3].forEach(function (negativeIndex) {
Object.defineProperty(Array.prototype, negativeIndex, {
get: function () {
return this[this.length + negativeIndex];
},
set: function (value) {
this[this.length + negativeIndex] = value;
}
});
});
var a = [1, 2, 3];
console.log(a[-1]); // 3
a[-1] = 10;
console.log(a); // [1, 2, 10]
@DavidBruant
Copy link

"this[this.length - 1]"
=> Shouldn't it rather be something like "this[this.length + negativeIndex]" (maybe a "%this.length". Debatable).

You could extend to any negative number with proxies. My array implementation with proxies: https://github.com/DavidBruant/ProxyArray (beware of potential handler API changes if testing somewhere else than FF4)

@DmitrySoshnikov
Copy link
Author

Yeah, true, a typo; thanks, fixed.

You could extend to any negative number with proxies

Yes, as I mentioned in the comment to the code, there is my implementation of negative indices based on proxies -- there of course we may handle any index -- https://github.com/DmitrySoshnikov/es-laboratory/blob/master/src/array-negative-indices.js And I made this custom implementation to exclude proxies overhead (usually as is said, we used only first three indices from the end). I saw yours implementation also when you mentioned it on es-discuss, also fits well. About potential changes to the API -- also true, but these are just experiments.

Dmitry.

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