Skip to content

Instantly share code, notes, and snippets.

@sonyseng
Last active November 10, 2015 04:54
Show Gist options
  • Save sonyseng/d13ce6dfa5e7fb67cd61 to your computer and use it in GitHub Desktop.
Save sonyseng/d13ce6dfa5e7fb67cd61 to your computer and use it in GitHub Desktop.
Use Generators to simplify the creation of an iterator in ES6 (babeljs)
// Test tree with contrived data
let testTree = {
value: 1,
child: [
{value: 2, child: [
{value: 7, child: []},
{value: 8, child: []},
{value: 9, child: []},
]},
{value: 3, child: []},
{value: 4, child: []},
{value: 5, child: []},
{value: 6, child: [
{value: 11, child: []},
{value: 12, child: []},
{value: 13, child: []},
{value: 14, child: []},
{value: 15, child: [
{value: 21, child: []},
{value: 22, child: []},
{value: 23, child: []},
]}
]}
]};
// Instead of constructing an iterable object using Symbol.iterator directly,
// using Generators cleans up the code nicely by hiding some of the details such as
// the next() method and the iterator result object.
function* treeIterator (tree) {
let nodeStack = [];
let node = tree;
while (node) {
yield node.value;
nodeStack = nodeStack.concat(node.child);
node = nodeStack.pop();
}
}
// We can use the new for .. of syntax to traverse an iterable object.
for (let value of treeIterator(testTree)) {
console.log(value);
}
// Output should be:
// 1
// 6
// 15
// 23
// 22
// 21
// 14
// 13
// 12
// 11
// 5
// 4
// 3
// 2
// 9
// 8
// 7
// Get the iterator out and call next() directly. Notice the generator returns
// an iterator for us. No need to access the Symbol.iterator method and call it directly.
let iterator = treeIterator(testTree);
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
// Output should be:
// {"done":false,"value":1}
// {"done":false,"value":6}
// {"done":false,"value":15}
// Flatten the tree using the spread operator. Combined with the
// rest operator destructuring to play around with the items in the tree.
let [a, b, c, ...rest] = [...treeIterator(testTree)];
console.log(a, b, c, rest);
// Output should be:
// 1 6 15 [23,22,21,14,13,12,11,5,4,3,2,9,8,7]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment