Created
August 9, 2010 15:52
-
-
Save sergeykish/515606 to your computer and use it in GitHub Desktop.
javascript generators
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
| Array.prototype.next = function() { | |
| if (this.length == 0) { | |
| throw StopIteration; | |
| } | |
| return this.shift(); | |
| } |
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
| describe("Array", function() { | |
| it("should iterator over array", function() { | |
| expect([1, 2, 3].nexts(2)).toEqual([1, 2]); | |
| }); | |
| it("should throw an error when list is over", function() { | |
| expect(function() { | |
| [].next() | |
| }).toThrow(StopIteration); | |
| }); | |
| }); |
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
| Object.prototype.nexts = function(count) { | |
| var list = []; | |
| try { | |
| for (var i = 0; i < count; i++) { | |
| list.push(this.next()); | |
| } | |
| } catch (err if err instanceof StopIteration) { | |
| }; | |
| return list; | |
| } |
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 Repeat(constructor) { | |
| this.itConstruct = function() { | |
| this.value = constructor(); | |
| } | |
| this.itConstruct(); | |
| } | |
| Repeat.prototype.next = function() { | |
| var value; | |
| try { | |
| value = this.value.next(); | |
| } catch (err if err instanceof StopIteration) { | |
| this.itConstruct(); | |
| value = this.value.next(); | |
| }; | |
| return value; | |
| } |
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
| describe("Repeat", function() { | |
| it("should repeat iterator", function() { | |
| it = new Repeat(function() { | |
| return [1, 2]; | |
| }); | |
| expect(it.nexts(3)).toEqual([1, 2, 1]); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment