Created
August 30, 2012 14:29
-
-
Save shamansir/3529641 to your computer and use it in GitHub Desktop.
Quick JS Iterator
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 iter(a) { | |
| if (a.__iter) { | |
| a.__iter.reset(); | |
| return a.__iter; | |
| } | |
| var pos = 0, | |
| len = a.length; | |
| return (a.__iter = { | |
| next: function() { | |
| if (pos < len) return a[pos++]; | |
| pos = 0; | |
| throw new StopIteration(); | |
| }, | |
| hasNext: function() { return (pos < len); }, | |
| remove: function() { len--; return a.splice(--pos, 1); }, | |
| reset: function() { pos = 0; len = a.length; }, | |
| get: function() { return a[pos]; }, | |
| each: function(f, rf) { | |
| this.reset(); | |
| while (this.hasNext()) { | |
| if (f(this.next()) === false) { | |
| if (rf) rf(this.remove()); else this.remove(); | |
| } | |
| } | |
| } | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment