Published
Edited
Sep 26, 2019
1 star
Insert cell
md`# Function Composition
Prompt: Create a javascript function which takes in a bunch of function as arguments and performs left to right composition on them. It then returns the result from a function which takes in a single argument on which it performs the composition.
## Approach 1: Currying and closures
`
Insert cell
compose = (...funcs) => {
return n => {
let result
funcs.forEach(func => {
result = func(result || n)
})
return result
}
}
Insert cell
md`## Approach 2: Reduce
`
Insert cell
composeViaReduce = (...fns) => val => fns.reduce((acc, fn) => fn(acc), val)
Insert cell
md `# Tests`
Insert cell
addOne = num => num + 1
Insert cell
substractTwo = num => num - 2
Insert cell
multiplyThree = num => num * 3
Insert cell
ltrComposition = compose(addOne, substractTwo, multiplyThree)
Insert cell
result = ltrComposition(4)
Insert cell
compose(addOne, substractTwo, multiplyThree)(5)
Insert cell
composeViaReduce(addOne, substractTwo, multiplyThree)(5)
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more