Can someone help me understand how this event handler is structured? Why do they have two arrow functions lined up?
const callAll = (...fns) => (...args) => fns.forEach(fn => fn && fn(...args));
It's a higher-order function - a function that returns another function. In this particular case, your function, when given an list of functions, returns a new function that applies these functions in turn to its argument(s). This higher-order function is usually called compose
or pipe
, because this is what it does - runs an argument through a series of functions, like unix pipes do (you know, like grep | sort | uniq
)
Note that your example is not particularly idiomatic, a better way to write it would be
pipe = (...fns) => x => fns.reduce((x, f) => f(x), x)
which can be used like
pipe = (...fns) => x => fns.reduce((x, f) => f(x), x) upper = s => s.toUpperCase() reverse = s => [...s].reverse().join('') bang = s => s + '!' convert = pipe(reverse, upper, bang) result = convert('hello') console.log(result)
It's a function that accepts n functions, and returns a function that when called with n arguments calls each of the supplied functions with those arguments.
Here's the code expanded:
// Accept functions function callAll(...fns) { // Return a function that accepts arguments return function (...args) { // Which, when called, calls each function with // those arguments fns.forEach(function (fn) { return fn && fn(...args); }); } }; const addOne = (n) => console.log(n + 1); const addTwo = (n) => console.log(n + 2); const addAllTheThings = callAll(addOne, addTwo); addAllTheThings(3);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.