6 kyu

Function composition

9,458 of 9,459matthewglover

Description:

Javascript functions can be combined to form new functions. For example the functions addOne and multTwo can be combined to form a new function which first adds one and then multiplies by two, as follows:

const addOne = (a) => a + 1
const multTwo = (b) => b * 2
const addOneMultTwo = (c) => multTwo(addOne(c))

addOneMultTwo(5) // returns 12

Combining functions like this is called function composition. Functional programming libraries in Javascript such as Ramda include a generic compose function which does the heavy lifting of combining functions for you. So you could implement addOneMultTwo as follows:

const addOneMultTwo = compose(multTwo, addOne)

addOneMultTwo(5) // returns 12

A simple implementation of compose, could work as follows:

const compose = (f, g) => (a) => f(g(a))

The arguments f and g are unary functions (i.e. functions which take one argument). The problem with this compose function is that it only composes two functions. Your task is to write a compose function which can compose any number of functions together.

Functional Programming
Fundamentals

More By Author:

Check out these other kata created by matthewglover

Stats:

CreatedNov 25, 2015
PublishedNov 27, 2015
Warriors Trained11932
Total Skips137
Total Code Submissions29074
Total Times Completed9459
JavaScript Completions9458
Total Stars63
% of votes with a positive feedback rating92% of 453
Total "Very Satisfied" Votes388
Total "Somewhat Satisfied" Votes56
Total "Not Satisfied" Votes9
Ad
Contributors
  • matthewglover Avatar
  • donaldsebleung Avatar
  • JohanWiltink Avatar
Ad