Last active
September 8, 2017 19:25
-
-
Save sudaraka/0c5cd9b1c30ca1b27763c6f1d51a659b to your computer and use it in GitHub Desktop.
General purpose JavaScript 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
/** | |
* compose.js: compose function & usage | |
* | |
* Copyright 2017 Sudaraka Wijesinghe <[email protected]> | |
* | |
* This program comes with ABSOLUTELY NO WARRANTY; | |
* This is free software, and you are welcome to redistribute it and/or modify | |
* it under the terms of the BSD 2-clause License. See the LICENSE file for more | |
* details. | |
* | |
*/ | |
const | |
compose = (...composableFunctions) => | |
(...argumentsOfComposedFunction) => composableFunctions | |
.reduceRight( | |
// return result as an Array to be spread in next call | |
(args, f) => [ f(...args) ], | |
argumentsOfComposedFunction | |
) | |
.pop() | |
// Usage | |
const | |
add = a => b => a + b, | |
add1 = add(1), | |
multiply = a => b => a * b | |
console.log( | |
compose(add1, multiply(5))(10) | |
) | |
// 51 | |
console.log( | |
compose(multiply(5), add1)(10) | |
) | |
// 55 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment