DEV Community

AC1556
AC1556

Posted on

Why I love pattern matching

This post can also be read over on my federated WriteFreely blog.

Why I love pattern matching

Last night I was playing around with some simple algorithm questions. The required language was good ol' JavaScript, but being a recent convert to Elixir and the functional programming realm, I went ahead and wrote solutions in both languages.

The question was to write a function that given an array, returns an array that contains cumulative sums.

i.e.:

cumlativeSums([1, 2, 3, 4, 5]) -> [1, 3, 6, 10, 15]
Enter fullscreen mode Exit fullscreen mode

Pretty standard coding assessment question. Deceptively simple, but not too hard that you can't solve it if you don't know it beforehand. There are also so many solutions out there for it. See this Stack Overflow question for inspiration.

JavaScript

Curry 🍛

Now, by far the coolest method you can do is use the native map function with Currying.

function sumArrayCurry(arr) {
  return arr.map(
    (
      (sum) => (value) =>
        (sum += value)
    )(0)
  )
}
Enter fullscreen mode Exit fullscreen mode

This happens to be the top-voted solution on Stack Overview, however, I'm not really a fan. It's honestly hard to read. If I came across this function in an actual codebase I would have to waste time trying to figure out what the hell it was doing. It's even worse if you don't have a strong grasp of what Curring actually is. Here's a link to a Stack Overflow explanation since Wikipedia is so dense.

Array.prototype.reduce

The method that came to mind when I first read the question was to use <some array>.reduce. From reading the question I know that I was going to have to do something to every element of the array and then return a new array containing the resultant values.

This sounds like it would be perfect for map since it returns an array, but reduce is nice since we can easily pass the cumulative sum to the next iteration of the call-back function. This doesn't mean that you can't use a map, just how my thought process worked.

function