Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Last active August 17, 2016 05:19
Show Gist options
  • Save DmitrySoshnikov/593e19f60df257f2119fad2e0431b617 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/593e19f60df257f2119fad2e0431b617 to your computer and use it in GitHub Desktop.
ES6 List negative indices
/**
* Reverse indices of Lists/Arrays in ES6.
*
* by Dmitry Soshnikov <[email protected]>
* MIT Style License
*/
'use strict';
class List extends Array {
peek() {
return this._reverseGet(1);
}
get '-1'() {
return this.peek();
}
get '-2'() {
return this._reverseGet(2);
}
get '-3'() {
return this._reverseGet(3);
}
set '-1'(v) {
return this._reverseSet(1, v);
}
set '-2'(v) {
return this._reverseSet(2, v);
}
set '-3'(v) {
return this._reverseSet(3, v);
}
_reverseGet(n) {
return this[this.length - n];
}
_reverseSet(n, v) {
return this[this.length - n] = v;
}
}
// -----------------------------------
// __tests__
let list = new List(1, 2, 3);
console.log(
list[-1], // 3
list[-2], // 2
list[-3], // 1
list.peek() // 3
);
list[-1] = 5;
console.log(list); // [1, 2, 5]
console.log(
list instanceof Array, // true
Array.isArray(list) // true
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment