Created
May 17, 2011 06:27
-
-
Save samyakbhuta/976042 to your computer and use it in GitHub Desktop.
nextInArray
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
/* | |
* Returns the next element in a function. | |
* Automatically rotates the index to the first element, if value matched the last element. | |
* If no match found for value returns the first element. | |
*/ | |
var nextInArray = function (value,anArray){ | |
//TODO : Check if anArray is really an array. | |
var index = anArray.indexOf(value); | |
if ( index == anArray.length-1 || index == -1 ) { | |
return anArray[0]; | |
} | |
else { | |
return anArray[(index+1)]; | |
} | |
} | |
//Usage | |
myArray = ["a","b","z"]; | |
nextInArray("a",myArray) // returns "b" | |
nextInArray("z",myArray) // returns "a" | |
nextInArray("1",myArray) // returns "a" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment