This isn't a great example for teaching currying. I think what the instructor/course is trying to get across here is that when you do:
let result = calculate(add, subtract, multiply)(1,3)
you're calling a function (calculate) that returns a function (one of the three you pass it, I guess picked at random though the assignment is unclear), and then you're calling that function (by using (1,3) on the result of the calculate(...) call.
calculate can be a one-liner:
function calculate(...fns) {
return fns[Math.floor(Math.random() * fns.length)];
}
or in ES5:
function calculate() {
return arguments[Math.floor(Math.random() * arguments.length)];
}
Live Example:
function add(num1, num2){
return num1 + num2;
}
function subtract(num1, num2){
return num1 - num2;
}
function multiply(num1, num2){
return num1 * num2;
}
function calculate(...fns) {
return fns[Math.floor(Math.random() * fns.length)];
}
let result = calculate(add, subtract, multiply)(1,3);
console.log(result);
A more useful example to teach currying would be:
let result = calculate(add, subtract, multiply)(1)(3);
// ----------------------------------------------^^
Notice that we're calling the result of calculate with 1, then calling the result of that with 3. Then, calculate would need to wrap the function it picks in another function that collects the 1 and then waits to be called with the 3:
function calculate(...fns) {
const fn = fns[Math.floor(Math.random() * fns.length)];
return (a) => {
return (b) => {
return fn(a, b);
};
};
}
or more concisely, but less clearly:
function calculate(...fns) {
const fn = fns[Math.floor(Math.random() * fns.length)];
return (a) => (b) => fn(a, b);
}
Live Example:
function add(num1, num2){
return num1 + num2;
}
function subtract(num1, num2){
return num1 - num2;
}
function multiply(num1, num2){
return num1 * num2;
}
function calculate(...fns) {
const fn = fns[Math.floor(Math.random() * fns.length)];
return (a) => (b) => fn(a, b);
}
let result = calculate(add, subtract, multiply)(1)(3);
console.log(result);
The function returned by calculate, when called, remembers a and returns a new function; that function, when called, gets b and calls fn(a, b) to get the result.
That example picks the function up-front, but it could pick it at the end as well:
function calculate(...fns) {
return (a) => (b) => fns[Math.floor(Math.random() * fns.length)](a, b);
}
Live Example:
function add(num1, num2){
return num1 + num2;
}
function subtract(num1, num2){
return num1 - num2;
}
function multiply(num1, num2){
return num1 * num2;
}
function calculate(...fns) {
return (a) => (b) => fns[Math.floor(Math.random() * fns.length)](a, b);
}
let result = calculate(add, subtract, multiply)(1)(3);
console.log(result);