Function Composition in JavaScript

Composing Functions is a great way to abstract two or more function under the hood. It is a great style to apply functions on your data. It is like the UNIX pipe command which takes the output of one command and applies it as input for the second command.
Function Composition of two functions f and g can be defined as `f(g(x))` where it will be evaluated from right to left.
x <- Your data
g <- Your First function
f <- Your Second Function
The order of evaluation in this case would be g(x) whose output would act as input to the function f.
const compose = f => g => x => f(g(x))
const add = x => x + 5
const multiply = y => y * 10
compose(add)(multiply)(2) 
This so compose(add) would return a closure and then we pass another function which will return a closure and then we pass data to be acted on.
 


  

Comments

Popular posts from this blog

Patroni, Docker Swarm, and the Silent Killer: A Deep Dive into MTU Mismatch

How to write a Git Commit Message?