Created
May 16, 2022 04:54
-
-
Save truongluu/585f326077611d0aecffbfba70155c2f to your computer and use it in GitHub Desktop.
Compose function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Composes single-argument functions from right to left. The rightmost | |
* function can take multiple arguments as it provides the signature for | |
* the resulting composite function. | |
* | |
* @param {...Function} funcs The functions to compose. | |
* @returns {Function} A function obtained by composing the argument functions | |
* from right to left. For example, compose(f, g, h) is identical to doing | |
* (...args) => f(g(h(...args))). | |
*/ | |
export default function compose(...funcs) { | |
if (funcs.length === 0) { | |
return (arg) => arg | |
} | |
if (funcs.length === 1) { | |
return funcs[0] | |
} | |
return funcs.reduce((a, b) => (...args) => a(b(...args))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment