DEV Community

Discussion on: Explain it to me like I'm five: .map, .reduce, & .filter edition

Collapse
 
nestedsoftware profile image
Nested Software • Edited

There are already some good comments others have made, but I'll add a small comment of my own. Here are two articles written by @machy44 where he implemented his own versions of map and filter. Maybe thinking about how you'd make your own version of these functions could be helpful:

A simple version of reduce would be implemented in a similar vein.

Here is a version of reduce I wrote for my article on asynchronous generators:

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

        accumulator = reductionResult

        yield reductionResult
    }
}

A normal synchronous version should be a pretty simple cleanup of the above code:

const syncReduce = function (iterable, reducer, accumulator) {
    for (const item of iterable) {
        const reductionResult = reducer(item, accumulator)

        accumulator = reductionResult
    }

    return accumulator
}

As @andeemarks points out, these functions basically abstract away the for loop boilerplate.

I thought I'd also add that these are not the only ways to do this kind of thing. For example, Python has list comprehensions that I think are often more clear. I don't think JavaScript has them though.