Here is the interview question prompt, presented for reference.
Composition is putting two or more different things together, and getting a combination of the inputs as a result. In terms of programming, composition is often used for combining multiple functions and getting a result at the end. Using composition leads to a cleaner and much more compact code.
If we want to call multiple functions, at different places in our application, we can write a function that will do this. This type of function is called a pipe
, since it puts the functions together and returns a single output.
A pipe function would have the following functionality:
Suppose we have some simple functions like this:
const times = (y) => (x) => x * y
const plus = (y) => (x) => x + y
const subtract = (y) => (x) => x - y
const divide = (y) => (x) => x / y
The pipe()
would be used to generate new functions:
pipe([
times(2),
times(3)
])
// x * 2 * 3
pipe([
times(2),
plus(3),
times(4)
])
// (x * 2 + 3) * 4
pipe([
times(2),
subtract(3),
divide(4)
])
// (x * 2 - 3) / 4
Can you implement a pipe()
function that will work as the examples stated above?
You can see the full challenge with visuals at this link.
Challenges • Asked over 3 years ago by Jake from AlgoDaily
This is the main discussion thread generated for Pipe Method (Main Thread).