Javascript Closures and Currying: part 2
Writing functions that are nested in a functional style in JavaScript can be tricky. For instance, consider the following code:
const composeu = (unaryFunc1, unaryFunc2) => {
return function(arg) {
return unaryFunc2(unaryFunc1(arg));
};
};
In order for this to work properly, the nested function invocations need to be written inside out. Existing functions can be effectively strung together/piped in a UNIX like fashion. The spread operator (...) allows for the number of functions chained to be variable.
In the following similar example, a function calling two binary functions are called on a set of arguments (known length) is returned:
const composeb = (binFunc1, binFunc2) => {
return function(arg1, arg2, arg3) {
return binFunc2(binFunc1(arg1,arg2), arg3);
}
}
You can also use these variables to control function flow, such as by storing a local variable. I wasn't able to figure out the following problem initially:
// Write a `limit` function that allows a binary function to be called a limited number of times
const limit = (binFunc, count) => {
return function (a, b) {
if (count >= 1) {
count -= 1;
return binFunc(a, b);
}
return undefined;
};
}