Created
October 13, 2012 09:33
-
-
Save wycats/3883958 to your computer and use it in GitHub Desktop.
Iterators in ES6 are, surprisingly, quite similar to the Ruby enumeration protocol
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
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; } | |
} |
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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...