Last active
May 14, 2017 18:50
-
-
Save MrJadaml/ff21ff621cef6117e3e43b9765c0e7ba to your computer and use it in GitHub Desktop.
A JavaScript method that will keep looping around an array, forward -- positive, or backward -- negative, when provided a valid or "out of bounds" index value.
This file contains 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
const array = ['rock', 'paper', 'scissors']; | |
function carouselIndex(idx, array) { | |
const negMap = { 1: 2, 2: 1, 0: 0 }; // go to sleep... make this dynamic to array size -- todo | |
if (idx >= 0) { | |
return array[idx % array.length]; | |
} | |
return array[negMap[Math.abs(idx % 3)]]; | |
} | |
// Tests | |
console.log( carouselIndex(0, array) ); // => "rock" | |
console.log( carouselIndex(2, array) ); // => "scissors" | |
console.log( carouselIndex(12, array) ); // => "rock" | |
console.log( carouselIndex(-1, array) ); // => "scissors" | |
console.log( carouselIndex(-8, array) ); // => "paper" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment