DEV Community

John
John

Posted on

It's allTrue... firststeps in functional JavaScript

Who is this for?

Anyone who is interested in functional programming at a beginner/intermediate level(whatever that means!) and will "listen" to my musings.

Kicking of with allTrue

Why allTrue? Well, allTrue is a function that combines predicate functions for logical conjunction. Also, by beginning with a function that starts with the letter 'a', this might be the start of a series of posts, and then again, maybe not, it kind of depends on you!

The function allTrue is my version of the Ramda function allPass. It uses the Array.prototype.every method, but that array does not contain primative values, but functions! I keep this function to hand in a file in my node_modules directory, I just call this file func.js. Yes, I know I could use Ramda, but at my stage in JS fp I just find it more helpful to either collect snippets from the web or write the functions myself. It just seems to make more impression on me and helps my learning process. As, does writing this post.

You should, of course, use Ramda in your production code as it has been "battle tested".

Here is the definition of allTrue.


 const  allTrue  =  curry((preds, x) =>  every(pred  =>  pred(x), preds))

Usage

An example is the best way to explain how to use allTrue.

Let's imagine we have an array of integers 1 thru 20 and we want only those integers between 5 and 15 that are even and just to make it slightly more interesting, we want to double those integers. I have in my func.js file the functions gt, lt and isEven and these function are curried by default, so I can write...


const { allTrue, compose, filter, gt, isEven, lt, map } = require('func')
const  integers  = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

const double = n => 2 * n
const  doubleEvensBetween5And15  =  compose(
  map(double),
  filter(allTrue([ isEven, gt(5), lt(15) ]))
)

So, you can see that allTrue takes a list(... a JS Array) of predicate functions that returns a predicate function which is then applied to the filter function. Finally, the result of this filter, which is the list of integers [6, 8, 10, 12, 14] is applied to map(double) to return [ 12, 16, 20, 24, 28 ].

Here is the function call.


  console.log(doubleEvensBetween5And15(integers))
  // => [ 12, 16, 20, 24, 28 ]

Visit working example at Runkit

It's all thanks to Curry

Yes, the programming world is indebted to Haskell Curry for his work in Combinatory logic and this important concept in fp takes his name.

I encourage you to read this post by Eric Elliott if you are not familiar with this fp practice.

If this post has been of interest to you please give it a like.

Cheers!

Also, I would like to hear any constructive criticism you may have with this post. Thanks.

Discussion (0)