concept curry in category javascript

appears as: curry
The Joy of JavaScript

This is an excerpt from Manning's book The Joy of JavaScript.

In this code, the higher-order function prop('funds') did not actually produce a result, only until map made use of it; thus, simulating a lazy or call-by-name strategy. This is convenient but at the expense of awkward notation having to write functions with expanded arrow syntax as in: const add = x => y => … or const prop = name => obj => ...You can automate this via the curry combinator.

The curry operator automates the process of dynamically converting a function of multiple arguments into several nested functions of a single argument. Thus, a function like add:

As wonderful and powerful as curry is, in JavaScript there are a few edge cases that can change the expected behavior of a function when it relies on features such as variadic parameters or parameters with default values.

For example, in listing 4.3, to make props work with curry, we needed to change ...names to a normal, non-variadic parameter names. The reason for this is that variadic parameters always need to appear at the end of the function signature.

Another use case that happens a lot is with functions that use default parameters. Looking at the implementation of curry above, you can see that it relies on Function.prototype.length. This property is a bit tricky in JavaScript, because it does not count functions with default values, as this snippet of code illustrates:

const add = (a, b) => a + b // add.length = 2
const add = (a = 0, b = 0) => a + b // add.length = 0

The way curry works is that it mandates you satisfy all of the arguments of a function before it evaluates. Until that happens, it keeps returning the partially applied functions with the remaining arguments waiting to be supplied. This is beneficial to avoid running functions with unsatisfied or undefined arguments. As I said earlier, add(3) returns back a function to the caller, but add(3, 7) evaluates to 10 immediately, and you don’t need the awkward set of parenthesis for each argument.

Figure 4.9 Compose with curry used in the implementation of calculateHash. The label above each box shows the complete function signature. “computeCipher” and “props” are curried and have been partially applied. The far right parameter (or the only parameter) of all functions is used to receive the input in one of functions in the chain

Functions like curry and compose, as used to drive the execution of calculateHash, are known as function combinators, which simply just mean functions that build up other functions. Combinators have no special logic of their own, they just work on the structure of the functions themselves. curry manipulates the arguments so that they can be evaluated one at a time. compose seamlessly threads through a function’s output with the next function’s input. All of this hidden from you. In this snippet of code: