Skip to content

Instantly share code, notes, and snippets.

@MarcelloDiSimone
Last active May 8, 2022 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarcelloDiSimone/4721772 to your computer and use it in GitHub Desktop.
Save MarcelloDiSimone/4721772 to your computer and use it in GitHub Desktop.
Taverse an Array circularly in both direction by adding prev and next methods to the Array prototype
function ExtendedArray() {
let arr = [];
arr.push.apply(arr, arguments);
arr.pos = 0;
arr.prev = function () {
return this[this.pos = (this.pos || this.length)-1];
};
arr.next = function () {
return this[this.pos = (++this.pos % this.length)];
};
return arr;
}
var a = ExtendedArray(1, 2, 3, 4, 5);
console.log(a.prev()); // 5
console.log(a.prev()); // 4
console.log(a.prev()); // 3
console.log(a.prev()); // 2
console.log(a.prev()); // 1
console.log(a.prev()); // 5
console.log(a.prev()); // 4
console.log('----------------');
console.log(a.next()); // 5
console.log(a.next()); // 1
console.log(a.next()); // 2
console.log(a.next()); // 3
console.log(a.next()); // 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment