Real Life Example

Sat, 09 Oct 2021 11:14:39 +0100

To understand the benefits we need a worthy real-life example.

For instance, we have the logging that formats and outputs the information. In real projects such functions have many useful features like sending logs over the network, here we’ll just use alert:

function log(date, importance, message) {
  alert(`[${date.getHours()}:${date.getMinutes()}] [${importance}] ${message}`);
}

Let’s curry it!

function log(date) {
            return (importance) => {
                return (message) => {
                    alert(`[${date.getHours()}:${date.getMinutes()}] [${importance}] ${message}`);
                }
            }
        }

Now we can easily make a convenience function for current logs

// logNow will be the partial of log with fixed first argument
let logNow = log(new Date());

// use it
logNow("INFO", "message"); // [HH:mm] INFO message

Now logNow is log with the fixed first argument, in other words, “partially applied function” or “partial” for short.

We can go further and make a convenience function for current debug logs:

let debugNow = logNow("DEBUG");

debugNow("message"); // [HH:mm] DEBUG message