Skip to content

Instantly share code, notes, and snippets.

@sudaraka
Last active September 8, 2017 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sudaraka/0c5cd9b1c30ca1b27763c6f1d51a659b to your computer and use it in GitHub Desktop.
Save sudaraka/0c5cd9b1c30ca1b27763c6f1d51a659b to your computer and use it in GitHub Desktop.
General purpose JavaScript compose function
/**
* compose.js: compose function & usage
*
* Copyright 2017 Sudaraka Wijesinghe <sudaraka@sudaraka.org>
*
* 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