Use JavaScript Generator To Kill Night King

So you know who killed Night King in Westeros. Only Valyrian steel can kill him, and Javascript can only kill mortals like you and me. In our JS land, Night King is a function who interacts with a generator function to illustrate a useful use case for generators in JavaScript.

Don't whine about the spoiler if you are a fan and not watched yet. This is a lousy screenshot from Twitter

Let's come back to the practical matter. I've thought about practical use case(s) for generator functions for a while, but couldn't find one that can't be implemented by pre-ES6 JS. For e.g., my first instinct was to build a factory for functions. The idea was to return a function based on the parameter passed to next() function.

However, this show-off is unnecessary. This can be implemented directly using a function as below:

Few folks suggested using it for asynchronous function call. However, async-await is readily available and crisp to use, so there's no need to re-invent it. It also seems like async function uses generator functions underneath.

So where would you need to use generator* function? 

Let's say you plan to build a program to simulate a battle between Starks et al. and Night King(NK). To simplify, let's say you'll have methods to represent each fictional character. You'll also have a method to decide and direct who'll attack Night King in the battle.
The method could start with favorite Jon Snow to attack NK and based on the impact it either assigns a different hero or continues to attack with the same fictional character. The key here is feedback from the method which represents Night King. The feedback passed via next() parameter interacts with expert logic in generator function to provide an optimal function to attack NK. The game continues until NK is dead, or you learn that he's powerful enough for you to give up. Code below:


You can go to github for full code or run  it on repl.it below.

The example I've provided is simplistic, but it can be extended to produce functions which produce functions. A generator provides a neat way to abstract all logic for producing functions like a factory pattern. The forte of a generator function is not any new feature it provides, but the ability to write readable code which is also correct most of the times.

Drop your comments to let me know what you think.

Comments

Popular Posts