Skip to content

Instantly share code, notes, and snippets.

@wycats
Created October 13, 2012 09:33
Show Gist options
  • Save wycats/3883958 to your computer and use it in GitHub Desktop.
Save wycats/3883958 to your computer and use it in GitHub Desktop.
Iterators in ES6 are, surprisingly, quite similar to the Ruby enumeration protocol
import { iterator, isStopIteration } from "@iter";
class Node {
constructor(item) {
this.item = item;
}
*@iterator() {
let node = this;
while (node && node.item) {
yield node.item;
node = node.next;
}
}
}
let list = new Node(1);
list.next = new Node(2);
list.next.next = new Node(3);
for (let item of list) {
console.log(item);
}
let gen = list[iterator];
try {
let item;
while (item = gen.next()) {
console.log(item);
}
} catch(e) {
if (!isStopIteration(e)) { throw e; }
}
class Node
attr_accessor :next
def initialize(item)
@item = item
end
def each
node = self
while node && node.item
yield node.item
node = node.next
end
end
# only let other Nodes see the `item` reader
protected
attr_reader :item
end
list = Node.new(1)
list.next = Node.new(2)
list.next.next = Node.new(3)
list.each do |item|
puts item
end
for item in list
puts item
end
enumerator = list.enum_for(:each)
begin
while item = enumerator.next
puts item
end
rescue StopIteration
end
# extra
enumerator.each do |item|
puts item
end
@machty
Copy link

machty commented Dec 31, 2012

How do you feel about StopIteration? Isn't it a little overkill to throw an exception and have to catch it just to terminate a loop, which was expected to happen anyway? Not to mention that afaik exception handling is (at least in < ES6) notably slower...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment