Created
January 14, 2015 20:10
-
-
Save ShivrajRath/4b5237a6ef2dbf5ca7a3 to your computer and use it in GitHub Desktop.
Array Iterator in Javascript
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
/************************************************************* | |
* Adds iterator to javascript Arrays | |
*************************************************************/ | |
/** | |
* Returns previous element in the iteration | |
* @return {[object]} [Returns null if iteration has not started or if limit has reached] | |
*/ | |
Array.prototype.prev = function(){ | |
if(isNaN(this.index) || this.index <=0){ | |
return null; | |
} | |
return this[--this.index]; | |
} | |
/** | |
* Returns next element in the iteration | |
* @return {[object]} [Returns null if iteration limit been has reached] | |
*/ | |
Array.prototype.next = function(){ | |
if(isNaN(this.index)){ | |
this.index = 0; | |
} | |
if(this.index >= this.length){ | |
return null; | |
} | |
return this[this.index++]; | |
} | |
/** | |
* Returns whether or not the iteration has more elements | |
* @return {[boolean]} [Returns true if the iteration has more elements] | |
*/ | |
Array.prototype.hasNext = function(){ | |
if(this.index < this.length){ | |
return true; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
doesn't iteration over key in any array instance now print
hasNext
,next
, andprev
as three always-present keys? Seems dangerous.minimal example: https://gist.github.com/endel/4136334