Currying Functions for Animals (and a singing robot)

Currying is a Functional Programming technique that can improve your code readability, reduce it’s length, diminish bugs but most importantly, known for causing you to fall in love with your code often.

Why Currying?

Suppose we have this data structure:

And suppose we must use selectAnimal() if we want to peek from the data structure, this can be reasonable if the structure is not exposed to us, or it is much more complex or large…

How can we take care of every animal in the zoo?
A procedural way to code it would be:

But this code has many disadvantages and duplicated segments that are not reused. Imagine what would happen if the list of animals was much longer. Of course we could loop over each type, but still the word zoo, for instance would appear several times. One could argue that zoo could have been a global variable for the function selectAnimal() but I disagree because I’d rather keep selectAnimal() a Pure Function for many reasons.

Notice the “salmon reptile” bug that is hiding like a needle inside a haystack in the code above.

Currying could help us solving these issues.

What is a Currying Function?

A Currying Function is converting a function with multiple arguments to a series of functions each accepts 1 argument, where each wraps the other. For example
(x, y, z) => z + y + z curried, would have been written like this:
x => y => z => x + y + z.
When you call it and send x, you get a function that accepts y, when y is sent, you get a function that accepts z, when z is sent then the answer returns.

How to Curry?

Lets use some Wrapper Functions on selectAnimal() and create a Currying Function:

or simply:

The entity above can be used in several ways:

Lets use this Currying Function to refactor the care taking code into something nice and less verbose.

Notice that the “salmon reptile” bug is less likely to happen in this code.

If we wanted to increase the reusabillity (degree of code reuse), a functional way to do so would be to create a high-order function like:

A high-order function is simply a function that either accepts a function as a parameter, or return a function or both.

The function takeCareMulti() is designed to take care of multiple animals, it accepts a typeSelector function, a typeCare function, and a list of animal names. Needless to say, It takes care on each animal.

Usage:

Notice the improvement from where we started. It is almost as if a robot is singing it. One could easily wrap each function to output its action and it would look like:

Summary

Use currying functions to increase code readability, reusabillity and your affection for the code. It might also decrease the length of your code and the chance to make a mistake.

where was that tiger all along?

namer

Out beyond ideas of wrongdoing
and rightdoing there is a field.
I’ll meet you there.

Rumi

ripple

Liked the article?

Subscribe

What is a Promise and how it works?

blog-promise1

First of all, I promise to implement a promise in this article.

What is a Promise?

The Promise object is used for asynchronous computations. A Promise represents a value which may be available now, or in the future, or never.

MDN

Example!

In the example above, the function given to the promise ctor is executed async. Also it is determined to have 2 parameters. These are callbacks in case of success or fail. Promises should supply a success value when resolved or failure reason when rejected.

Don’t be intimidate by the arrow functions if you aren’t familiar with them
(parameter) => {/*action*/}
is equivalent to
function(parameter) {/*action*/}

Using the code above would be done by chaining the functions then and catch like that:

The function passed to then() will be invoked with an answer if the promise is or will be resolved. The function passed to catch() will be invoked with a reason if the promise will eventually reject. This way you can relate any async post-action to your code.

How promises work?

Well first, you have to keep’em 🙂

Let’s implement a very simple promise so we could have a better understanding on the basis of what is going on inside. Code followed with deep explanation:

First thing to notice is that when created a new instance of edge64Promise then given parameter action is immediately executed async. This is done by:

action is invoked with two private functions that edge64Promise delivers, resolve() and reject(). I’ll examine one of them, since both are really similar:

resolve() will be executed by the promise’ user when a promise resolves, hence it has an answer parameter. This answer is stored because it is not clear whether or not, at this point the then() is executed. If it isn’t, we are not really sure what to do with the answer and we must wait until then() is invoked. However, if then() is already invoked, then that.resolveCallback would be defined, and so we can call it.

Notice the use of that instead of this, I use it as a conversion in any class function/method in order to prevent context confusions which can happen a lot in JavaScript

At the moment when then() is invoked, we aren’t sure that the promise is resolved with an answer. If it is, we have two parts of the whole, the callback function and the answer to send to it, otherwise, we must store the callback function in case the promise will resolve.

We return that in order to allow chaining the catch() afterwards.

Note: I’ve explained the most plain and simple way of using promise. For instance, Notice that in my implementation you can’t chain .then() twice, and this option is important for other coding techniques which I will might post about in the future.

Summary

Promise will help you control an async code.

The trick in implementing a class like Promise is to realize that resolve() and then() relay on each other. resolve() misses the callback function and then() misses the actual answer. Same goes to reject and catch() but with reason, instead of answer.

How to never use loops again with map, filter and reduce?

Here is a piece of code, it’s purpose is to manage employees’ salary bonuses due to holidays.

Was it ugly? Was it difficult to follow? Were there too many variables? And isn’t it too much verbose? The main problem with this code is that it is not straight to the point.

Lets refactor it so it could lose some sense of repetitiveness.

Replacing loops with map filter & reduce

Here is an alternative nice code:

I successfully eliminated any usage of loops. Notice how short it is. Notice that we got rid of variables such as extra, newEmps and others. The code is less verbose, it is straight to the point.

Now let’s dive deep on how each of the function refactored, so we could have some better understanding on map, filter & reduce.

Filter

Filter loops over a list and checks each item with a predicate function. If the function returns true, the item remains, otherwise it is filtered. An example:

Boys are persons who are children and males.

If you are not familiar with arrow functions whey are kinda nice, a synonym statement would have looked like this:

Map

Map loops over a list and apply a function on each item. All of the results are collected into a new list that returns. An example:

Men are grown boys.

Notice that hopefully grow is a pure function and thus, boys and men are two different lists.

Reduce

Reduce loops over a list and returns a single value out of it. Depending on an iteratee function sent, reduce sums, multiplies or does any other operation. Example:

In the example above, if population consists of 4 people, then iteratee function would have been called 4 times. In other words, if we called the ireratee function countSavings, for the sake of example, then the above reduce function produces the same value as this code:

Bonus Section – How to avoid looping over functions?

If some of the things are still unclear at this point, it is a good idea to read again the salary example refactored and examine it a little further.

Lets go back to our salary example above. Say that salary calculation task was way more complex, in fact it is. If in order to calculate it, we would need a vast amount of functions, how would we do it?

Assuming emp has an array of salary transactions, something like:

Then surely we had to loop over this functions and

Don’t be so sure. There is also a way to eliminate this loop away. Read carefully and twice:

Lets examine the expression above, beginning with (arg, func) => func(arg):
This function accepts two parameters, first is an argument, second is a function. The return value is that which the function (2nd parameter) will return when given the arugment (1st parameter). So for instance, if we call this weird entity kindDavid just for the sake of example, then:
kingDavid(3,x=>x+4) is 7
and
kingDavid(13.5,x=> x==13.5) is true
and more importantly
kingDavid(emp, calculateSalary) is calculateSalary(emp)

Because calculateSalary is a function returning a new emp object it can work perfectly with reduce. First iteration will apply: (emp, emp.transactions[0]) which will return emp.transactions[0](emp). This is actually a new emp with calculated salary. It is now to be sent as a first argument in (result, emp.transactions[1]), which will return emp.transactions[1](result), and so on… Until all the transaction functions applied on a single emp.

The below code emphasizes it:

Want to know more?

Hit

npm install lodash --save

Then

const _ = require('lodash');

And play with it. Full documentation is here.

Summary

If you don’t like your code too straight to the point, use loops.

Subscribe