0

I needed to create a lot of entities in arrays at my job, and some guy said to me use this library to use "pattern matching" in my pull request instead creating manually the arrays an populating it.

We have to create a lot of things, eg. of user:

function createUser(id){
  return {
    id: id
  }
}

var users = createStuff(createUser, 50);

what I did to populate:

function createStuff(createFunction, howManyTimes){
  var createdStuffs = [];
  for(var i = 0; i < howManyTimes; i++){
    createdStuffs.push(createFunction(i));
  }

  return createdStuffs;
}

what he asked me to do with pattern matching:

function createStuff(createFunction, howManyTimes){
  return howManyTimes.matches(
    (x = 0) => [],
    (x)     => [createFunction(x)].concat(createStuff(createFunction, x - 1))
  )
}

What is the benefits about this pattern matching? I do understand the recursive calling on his example which replaces the for loop, but I think my example is easier to read though all the creation logic is basically written at a single line at his example.

I'm asking explanations about this and most people are telling me "it's better because is functional and have less moving parts", is this really true? I don't agree with him and I'd like explanations or arguments to tell he's wrong

  • The code you've written (with the for loop) is almost certainly faster than the pattern matching code. The pattern matching example will probably be MORE confusing to most javascript developers unless they have encountered pattern matching before (in a language such as Haskell), or learned the pattern on their own. – Erik Christianson Sep 01 '16 at 18:29
  • 2
    You might want to have a look at [Is there a mechanism to loop x times in ES6 without mutable variables?](http://stackoverflow.com/q/30452263/1048572). That "pattern matching" thing is quite horrible (using dark and *really* inefficient magic). If you want to use recursion and `concat`, at least use a simple if-statement. – Bergi Sep 01 '16 at 20:10
  • 1
    I agree with @bergi – there is some really nasty stuff happening in that library. – Thank you Sep 02 '16 at 02:46

1 Answers1

1

Your colleague has taken the quite correct premise that immutability and a functional style is beneficial and drawn a very incorrect conclusion that any immutable solution employing a functional style is superior. Readability is important and possible in any paradigm.

A proper functional solution using underscore.js with all the benefits and none of the eye-gouging readability issues would look like:

var users = _.map(_.range(howManyTimes), createUser);
Karl Bielefeldt
  • 42,558
  • 9
  • 56
  • 88