DEV Community

Cover image for Lazy Evaluation in JavaScript with Generators, Map, Filter, and Reduce

Lazy Evaluation in JavaScript with Generators, Map, Filter, and Reduce

Nested Software on February 27, 2018

My friend edA-qa was recently doing some programming live using the Rust language on twitch. An interesting bit of code came up: (1..).filter(|n...
Collapse
 
murjam profile image
Mikk Mangus

Well done! But wouldn't it make even more sense when the whole statement would be executed one item by one. So next() wouldn't gather all the responses of the iteration into an array, but would have the ability to evaluate an expression defining how many times to call it. So, for instance a sum could stop while reached some value.

Collapse
 
nestedsoftware profile image
Nested Software • Edited

Thanks for your comment! While this code is lazy, it's still completely synchronous. So once take is called, it has to run to completion - calling next only processes one item, but I think you meant to say take. I wonder if you mean that this code could be implemented asynchronously. I did implement a simple asynchronous reduce for another article:

const asyncReduce = async function* (iterable, reducer, accumulator) {
    for await (const item of iterable) {
        const reductionResult = reducer(item, accumulator)

        accumulator = reductionResult

        yield reductionResult
    }
}
Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

Playing with infinite lists is fun! :)

Collapse
 
machy44 profile image
machy44

Very interesting post. A lot of new stuffs which I didn't know. Good job.

Collapse
 
karoldepka profile image
Karol Depka Pradzinski

Fun Fact of The Day: Carlos Ray Norris iterated over (1..), twice.