Last active
May 8, 2022 21:26
-
-
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
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
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