Description
The callAll
utility is a higher-order function that creates a new function which executes multiple functions
in sequence with the same arguments. Itβs particularly useful for combining event handlers or callbacks.
Key features:
- Accepts any number of functions as arguments
- Returns a new function that can accept any number of arguments
- Executes each provided function (if it exists) with the given arguments
- Safely handles cases where some functions might be undefined or null
Code Byte
// π° Here's a little utility that might come in handy
// It accepts any number of functions which returns a function which accepts any number of arguments.
// And for each of the function, it's going to call it if it exists with the arguments.
const callAll = (...fns) => (...args) => fns.forEach(fn => fn && fn(...args));
Use cases:
- Combining multiple event handlers in React components
- Implementing middleware-like patterns
- Extending existing functions without modifying their original implementation
Example usage:
const onClick = callAll(
() => console.log("Clicked!"),
props?.onClick,
analytics?.trackClick
);
// When onClick is called, it will:
// 1. Log "Clicked!"
// 2. Call props.onClick (if it exists)
// 3. Call analytics.trackClick (if it exists)