Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compose functions from left to right and right to left
// Compose function from right to left. a.k.a. normal 'compose' in functional programming
function composeFromRight(...fns) {
return (initialVal) => fns.reduceRight((val, fn) => fn(val), initialVal)
}
// Compose functions from left to right. a.k.a. normal 'pipe' in functional programming
function composeFromLeft(...fns) {
return (initialVal) => fns.reduce((val, fn) => fn(val), initialVal)
}
// Functions to compose
function add2(n) {
return n + 2
}
function add4(n) {
return n + 4
}
function times2(n) {
return n * 2
}
// Functions are applied right to left
var times2add2Right = composeFromRight(add2, times2)
var add2add2add4Right = composeFromRight(add4, add2, add2)
// Call functions
console.log('times2add2Right', times2add2Right(2)) // 6
console.log('add2add2add4Right', add2add2add4Right(2)) // 10
// Functions are applied left to right.
var times2add2Left = composeFromLeft(times2, add2)
var add2add2add4Left = composeFromLeft(add2, add2, add4)
// Call functions
console.log('times2add2Left', times2add2Left(2)) // 6
console.log('add2add2add4Left', add2add2add4Left(2)) // 10
/*
Values are the same and composeFromLeft is easier to read
¯\_(ツ)_/¯
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment