Last active
January 30, 2021 22:35
-
-
Save DavidWells/c236f5510230e8d69b6e0523357c7a30 to your computer and use it in GitHub Desktop.
Compose functions from left to right and right to left
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 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