Utilizing ES6 Generator

I am going through Mozilla documentation about the Iterator and Generator concept introduced in ECMAScript6. Here is the overview as per Mozilla JS guide

Processing each of the items in a collection is a very common
operation. JavaScript provides a number of ways of iterating over a
collection, from simple for loops to map() and filter(). Iterators and
Generators bring the concept of iteration directly into the core
language and provide a mechanism for customizing the behavior of
for…of loops.

This post is not about how it works, it is better explained at Mozilla JS guide.

I have tried to apply the JS generator for one of the our day to day code. I think it is better suitable for lazy traversing and evaluating each item and proceed further if required. A common example comes in my mind is the tree traversing. I have implemented Depth First Search ( pre-order) using generator.

Consider the scenario where you need to traverse the tree node, evaluate/process the node and go further for next node. The code is as simple as below

var tree = getTree();
for (let node in tree.dfs()){
    // process node.
}

Isn’t above code super simple to understand, all traversing code it hidden, no need to manipulate the index/pointer etc.

Here I wrote simple traversing code that uses generator that return each node one by one.

function constructTree(values) {    
    return {
        dfs: function* (index) {
            if (!index) index = 0;
            yield values[index];
            if((2 * index + 1) < values.length)
                yield* this.dfs(2 * index + 1);
            if((2 * index + 2) < values.length)
                yield* this.dfs(2 * index + 2);

        }
    }
}

var tree = constructTree(values); 
for (let val of tree.dfs()) { 
   //process val
}

Here I am expecting the tree structure in an array. You can notice new syntax has been introduced function* to represent iterator/generator for the given JS object.

A generator is a special type of function that works as a factory for
iterators. A function becomes a generator if it contains one or more
yield expressions and if it uses the function* syntax.

The complete example is available at fiddle

Comments

  1. Bigo Live Mod APK is a unique live streaming app that gives you the ability to broadcast your gameplay live to the world. With Bigo Live Mod, you can easily create and join custom games with your friends, or challenge other players to matches of your own creation. The app is free to download and use, and there are no in-app purchases or ads. For more Info visit us at https://apkranch.com/bigo-live-mod-apk/

    ReplyDelete

Post a Comment

Popular posts from this blog

Composite Design Pattern by example

State Design Pattern by Example

Eclipse command framework core expression: Property tester