Skip to content

Instantly share code, notes, and snippets.

@samyakbhuta
Created May 17, 2011 06:27
Show Gist options
  • Save samyakbhuta/976042 to your computer and use it in GitHub Desktop.
Save samyakbhuta/976042 to your computer and use it in GitHub Desktop.
nextInArray
/*
* 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