I went trough ES6 features and Generators caught my eye. One thing that sprang to mind is chaining Promise objects, that I could not do with loops. What other mechanics we will be able to do, that we could not before?
I do understand this is broad question, still I can't think of anything but Promises at the moment.
By using yield, generators can be suspended at any point in the control flow of your function, saving your current state of execution (scope & stack).
Without generators, this is more complicated:
Generators are generically useful for traversing data structures, creating a simple stream-like iterator that yields all elements in order. Think of tree traversal, or DFS/BFS in graphs for simple examples.
function* traverseTree(node) {
if (node == null) return;
yield* traverseTree(node.left);
yield node.value;
yield* traverseTree(node.right);
}
// vs (not sure):
function traverseTree(node) {
var rl, l, r;
return {
next: function() {
if (node == null && !r) return {done:true};
if (!l) l = traverseTree(node.left);
if (!(rl=l.next()).done)
return rl;
if (node != null) {
var n = {value:node.value};
node = null;
r = traverseTree(node.right);
return n;
}
return r.next();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With