JavaScript Monads part 4

Mbedingfield
3 min readDec 4, 2022

--

I hope you have been following this post which starts here.

Let’s move on shall we? I wanted to show a way of using point free programming, although, I must admit, this is not my preferred way but a lot of people may prefer this method so I decided to give it a shout.

This is going to be a way of passing higher order functions so that the mapping process will automatically feed the results of the previous function into the next function. Let’s take a look.

Let’s create a new file called utils.js and place this code inside of it:

const prop = (propName) => (obj) => obj[propName];
const append = (appendee) => (appendix) => appendix + appendee;

Let’s talk about these a little bit. prop is a function that takes and argument (propName) and returns a function that takes and argument (obj) and that function returns the property of that object. So, if we have and object that looks like our a object we have been usig, then calling

console.log(prop('b')(a));

This should print

my code

Let’s now import these two functions into our index.js so we can use them

Ok, I know, once you save, your console is throwing a fit because you have variables that you have declared that you are not using. That only is accurate if you are using my setup instructions of course. We can change that a couple of ways. You can either comment out the imports until you actually using them or we can change the eslint config. Let’s open up eslintrc.json file and make this change:

"react/prop-types": 0,
"react/react-in-jsx-scope":0,
"no-console": 0,
"no-debugger": 1,
"no-unused-vars": 0

The no-unused-vars is the one we are adding. Now you will have to kill webpack and then run npm start again, but now your console should be clean even with the unused variable declaration.

Now, everything should be good.

The append function takes in an argument(appendee) and returns a function that expects and argument(appendix) and then just returns the contatenation of the two. So, now we can put these guys to use:

const maybeA = Maybe.just(a)
.map(prop('b'))
.map(prop('c'))
.map(append(' works perfectly again'))
.extract();

We can of course remove the test line for our prop example:

// console.log(prop('b')(a));

This was just an example, but the code still works fine:

I’ll be honest, I’m not the biggest fan of this approach. For me, this might look hard to read. We know that Maybe is holding an a, but a year from now, this might confuse us when we come back to this code. I promise, I will come back and show you an acceptable and much easier to ready way, but I figured, some people would like this approach.

Read the next story and we’ll dig a little deeper into our Maybe function.

--

--