+ 7
What are some real life applications of generators in Javascript?
Generators
8 odpowiedzi
+ 3
Generators are like lists but you don't have to generate the whole list at once which potentially saves time.
function* foo () {
for (let i = 0; i < 100; i++)
yield long_computation(i);
}
Now, `[...foo()]` gives a list of length 100 with all the results but you can also stop earlier:
for (let value of foo())
if (value < 0)
break;
This is better than generating the whole list which takes a long time and then throwing away the last 90 elements!
Some things we can do with generators:
- Infinite generators, like a generator that generates all possible prime numbers, one after the other.
- Take input multiple times:
function* chatBot() {
const age = yield "Please enter your age: ";
const name = yield "And your name: ";
return "Thanks!";
}
let bot = chatBot();
let input, msg;
while (true) {
let { value, done } = bot.next(input);
msg = value;
if (done) break;
input = prompt(msg);
}
alert(msg);
And many other things but I'm running out of space.
+ 4
Schindlabua yeah thanks. I understand generators but I don't know how useful they are. For example when I learned promises, I applied it in nodejs when I was working with APIs but for generators, apart from infinitely producing some values one at a time, I don't know other applications of it.
+ 4
Schindlabua Thanks very much 😊 ❤️
+ 3
Andrei I es6 generators
+ 3
Edward We can draw parallels here. If promises are a replacement for nodejs-style callbacks, then generators can serve as a replacement for finite-state machines.
And those are everywhere. Say in a function that models a game of chess you would need to pass in whose turn it is, as an argument, but a generator can just remember it.
I think generators are a bit under-utilized and not so mainstream (yet!) and so they don't come up in my day-to-day programming a lot either. But you can find many cool applications for them if you keep an eye out.
(Performance is pretty bad if you yield a lot so that sucks)
Also nice: async generators are a thing now so we have even more ways to deal with Promises and such.
Another tool in the toolbox am I right :)
+ 2
Generators of what?
+ 2
Mirielle That sounds plausible. Thanks a lot. 😊😊