Created
May 21, 2011 21:32
-
-
Save DmitrySoshnikov/984921 to your computer and use it in GitHub Desktop.
Manual negative indicies of arrays in ES5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 <[email protected]> | |
* 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] |
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
"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)