function createMathOperation(operator) {
console.log(operator); //(augend, addend) => augend + addend
return (value, other) => {
return operator(value, other)
}
}
const add = createMathOperation((augend, addend) => augend + addend)
add(1,2)//3
I found the above function definition from lodash
. I am trying to understand it but to no avail.
Right inside createMathOperation
, I try to log operator
and this is the value
(augend, addend) => augend + addend
I guess value
and other
is 1
and 2
but how?
And how return operator(value, other)
works when operator
is (augend, addend) => augend + addend
Can anyone convert it to longer human readable form for a better understanding instead?
This is the essence of functional programming you can pass in a function, return a function, and call the function you received as a parameter:
function createMathOperation(operator) {
console.log(operator); // This is a the function that performs the computation
// We return a new function (using arrow syntax) that receives 2 arguments and will call the original operator we passed in to createMathOperation
// The code inside this function is not executed here, the function is not invoked.
// The caller can take the returned function and executed 0-n times as they wish.
return (value, other) => {
// when we invoke add this is the code that gets called and the arguments we pass to add end up in value and other
console.log("Getting ready to compute " + value + " operator " + other);
return operator(value, other) // since operator is a function we just invoke it as we would any other function with the two arguments we got from whoever called us.
}
}
// add will contain the wrapped function that has our extra console.log
const add = createMathOperation((augend, addend) => augend + addend)
// The 'Getting ready ...' text has not been printed yet, nobody invoked the function that was returned yet, the next line will do so.
console.log(add(1,2))
// will output:
// Getting ready to compute 1 operator 2
// 3
A note on =>
is just syntactic sugar over a function
expression, it has extra semantics around this
, but for this example, (augend, addend) => augend + addend
is equivalent to function (augend, addend){ return augend + addend; }
createMathOperation returns function, which adds two numbers. Here's more readable version:
function createMathOperation(fn) {
console.log(fn);
return function(value, other){
return fn(value, other);
};
}
const add = createMathOperation(function (augend, addend) {
return augend + addend;
});
add(1,2)//3
I renamed 'operator' to 'fn' to make it less confusing (syntax highlighting colored it blue for some reason).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With