Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Is there any "python's Generator" equivalent in JavaScript?

Is there any "python's Generator" equivalent in JavaScript?

PS: Python's Generator is very memory efficient when we need to do one time iterate through a big array, hash...
"Generators are iterables, but you can only read them once. It's because they do not store all the values in memory, they generate the values on the fly"

(Python's Generator explained in this thread: What does the "yield" keyword do in Python? )

like image 502
JackSMTV Avatar asked Oct 27 '25 15:10

JackSMTV


1 Answers

Not in a standard way. Some browsers already implement python-style generators, but they require extensions that need to be explicitly activated. There are proposals to add generators to a next version of the ECMAScript spec, but I wouldn't see that being useable very soon.

So far, the best you can do is to use the old school external iterator pattern. It is just as powerful, although it is a pain to write in more complicated cases.

like image 65
hugomg Avatar answered Oct 29 '25 04:10

hugomg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!