Skip to content

Instantly share code, notes, and snippets.

@huozhi
Created February 26, 2017 06:02
Show Gist options
  • Save huozhi/331b88821389b3e739c7c76dc14c66f4 to your computer and use it in GitHub Desktop.
Save huozhi/331b88821389b3e739c7c76dc14c66f4 to your computer and use it in GitHub Desktop.
chained multiple functions
/**
* https://github.com/react-bootstrap/react-bootstrap/blob/master/src/utils/createChainedFunction.js
* Safe chained function
*
* Will only create a new function if needed,
* otherwise will pass back existing functions or null.
*/
export function chainFunctions(...funcs) {
return funcs
.filter(f => f != null)
.reduce((acc, f) => {
if (typeof f !== 'function') {
throw new Error('Invalid Argument Type, must only provide functions, undefined, or null.')
}
if (acc === null) {
return f
}
return function chainedFunction(...args) {
acc.apply(this, args)
f.apply(this, args)
}
}, null)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment