Skip to content

Instantly share code, notes, and snippets.

@sergeykish
Created August 9, 2010 15:52
Show Gist options
  • Select an option

  • Save sergeykish/515606 to your computer and use it in GitHub Desktop.

Select an option

Save sergeykish/515606 to your computer and use it in GitHub Desktop.
javascript generators
Array.prototype.next = function() {
if (this.length == 0) {
throw StopIteration;
}
return this.shift();
}
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);
});
});
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;
}
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;
}
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