loading...

re: Understanding Generators in Javascript - Javascript weekly VIEW POST

FULL DISCUSSION
 

I thought generators is more like a funny toy in javascript. They have interesting concept, but almost useless in the real code. It's a surprise for me that this language feature has a real use case in redux-saga!

 

Yeah true. it is one of the powerful features in javascript. sadly, it is not being used that much. but, redux saga using it in an efficient way possible.

 

Never needed them so far, but I do use a lot of promises.

 

Generators are almost identical to enumerables in C#, the real benefit of it is reduce number of iterations. Consider following,


   // a is an array of elements

   a = a.filter((e) => some condition ....);

   if (some other condition) {
       a = a.filter((e) => some other condition ... );
   }

   enumerate a....

In above example, a is iterated 3 times,

But with generators, you can reduce iteration to single iteration.


   ga = *(a) => for(let i=0; i<a.length; i++) {
      console.log("iterating");
      yield return a[i];
   };

   filter = *(ga, filter) => { const g = ga(); while(g.next()) if (filter(g.value) yield return g.value; };


   a1 = filter(ga, (s) => s ... condition 1);
   a2 = filter(a1, (s) => ... condition 2);

   for(let item of a2) {
   }


If you run this code, you will notice that iterating is only printed once.

You can combine various map/filter or map/reduce to only iterate an array once.

 

Thanks for the example. The same result might be achieved by iterating the array with the old-school for loop. The array will be iterated only once as well.

for (let i = 0; i < a.length; i++) {
  if (!condition1) continue;
  if (!condition2) continue;
  doSomethingWith(a[i]);
}

I see that generators help to write code in FP-style and save iteration cycles at the same time.

This is only possible when you have your conditions when you want to iterate it, imagine series of function passing each other generators, and final evaluator does not have access to all conditions.

Conditions functions should exist somewhere. I think it's always possible to refactor the code and have access to these functions (for example, by moving the conditions functions higher in lexical scope).

 

Good example and explanation. :-)

code of conduct - report abuse