Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Taverse an Array circularly in both direction by adding prev and next methods to the Array prototype
Array.prototype.pos = 0;
Array.prototype.next = function () {
return this[this.pos = (++this.pos % this.length)];
};
Array.prototype.prev = function () {
return this[this.pos = (this.pos || this.length)-1];
};
var a = [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
You can’t perform that action at this time.