Yield - Generator Functions

The generator functions provide a simple way to program a iterator using native resources of the java script programming language. It provide a simple syntax for blocking and continue the flow of a function executing based on interactions with this function.

It is quite useful to any function that has to process a certain dataset, but just a part by time, optimizing the processing and memory consumption.

A generator function is a normal java script function that has a “*” at the side of the function name. It means this function when being its execution is allowed to stop in a blocking way, as soon as it found the yield keyword. In this moment the value that the right of yield is returned, and the function execution is blocked until this function is called gain through the .next() method.

function* generator_function(index) {
    while (index < 2) {
      yield index;
      index++;
    }
  }

 The value at the right of yield statement can be read by the .value property.

  const iterator = generator_function(0);//seed

  console.log(iterator.next().value); // output: 0

Then it will keep executing in this way while the yield statement is found. The only way a generator function is concluded is:

a)      The function reaches its end – the undefined value is returned.

b)     The function explicitly return a value with the return keyword.

c)      Some exception is throw.

You can see on example of this code at this link:

https://github.com/rafaelqg/code/blob/main/generator_function_yield.js

A video class is also available here:



Comments

Popular posts from this blog

HASHLIB: Using HASH functions MD5 and SHA256

Spread Operator

Dart: implementing Object Oriented Programming (OOP)