Map, Filter, Reduce vs For Loops (syntax)

JavaScript Joel on November 21, 2018

The intention of this post is not to say one paradigm is better than the other. It is just to show common imperative patterns you run into and thei... [Read Full]
markdown guide
 

Nice comparison, also the last functional example can avoid the if statement :

const isEven = x => x % 2 === 0
const double = x => x * 2
const input = [ 1, 2, 3, 4, 5 ]
const initial = []

const reducer = (filter, map) => (acc, x) =>
  filter(x) ? acc.concat(map(x)) : acc

const output = input.reduce(reducer(isEven, double), initial)

output //=> [ 4, 8 ]
 

I was trying to keep it simple for noobs but I think your solution is much cleaner.

Typically I will use a mutable accumulator in a reducer. Your version is immutable so every iteration will produce a new array. Not the best for performance but this is just for example anyway.

 

Hi Joel,

I'm one of those noobs, but trying my very best not to be. I am trying to teach myself functional programming in JavaScript and I have come upon the subject of transducers. This code looks very similar; can you confirm that this code is, or is closely related to the concept of transducers.

Thanks

Transducers are the next evolution. You would start with a list, and learn map, filter, reduce. Once you start applying multiple map/filter/reduces to a single list, you realize you are enumerating the list multiple times, which will slow down your application.

Transducers are a way to apply those multiple map/filter/reduces while enumerating the list one time.

 

Then with a mutable accumulator :

const reducer = (filter, map) => (acc, x) =>
  (filter(x) && acc.push(map(x)), acc)

Awesome!

I'm a big fan of the comma operator. I decided to leave it out in this code block to not confuse anyone. But I use it pretty regularly in my own codebase.

 

Ternary operator it's still an if statement in disguise.

 

Not exactly, an if statement doesn't evaluate to a value, in other words, it doesn't return anything.
The ternary evaluates to something.
medium.com/javascript-scene/nested...

 

It's all functional.
Comparison between Imperative vs Declarative.

 

I still fight with this (though in Kotlin, not JavaScript). OOP/procedural style is much convenient, but I do understand importance of declarative coding because it's much more elegant and pure.

 

I'd like to argue that imperative code isn't any more convenient, but that it is more familiar.

If you had learned a declarative style first you would feel the same way about oop.

 

Hmmm...probably correct. I have not thought about it in this way.

code of conduct - report abuse