DEV Community

jser
jser

Posted on • Edited on

BFE.dev challenge #11. what is Composition? create a pipe()

https://bfe.dev is like a LeetCode for FrontEnd developers. I’m using it to practice my skills.

This article is about the coding problem BFE.dev#11. what is Composition? create a pipe()

Alt Text

Look at the interface

/**
 * @param { Array<(arg: any) => any> } funcs 
 * @returns { (arg: any) => any }
 */
function pipe(funcs) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

We need to chain the functions up into one function, obviously closure is needed.

Start coding

First, return an empty function, which accept the argument

function pipe(funcs) {
  return function(arg) {
    // TODO: get the result together with funcs
  }
}
Enter fullscreen mode Exit fullscreen mode

To chain the functions up, we could declare a result, and apply all the functions to this single result.

function pipe(funcs) {
  return function(arg) {
     let result = arg
     for (let func of funcs) {
       result = func.call(this, result)
     }
     return result
  }
}
Enter fullscreen mode Exit fullscreen mode

notice we don't use arrow function in order to keep the right this.

That's it pretty easy!

Use reduce

When we find a result and a for loop, it is a clear sign that reduce could be used.

It doesn't change anything, just a little fancier. Let' rewrite it.

function pipe(funcs) {
  return function(arg) {
     return funcs.reduce((result, func) => {
       return func.call(this, result)
     }, arg)
  }
}
Enter fullscreen mode Exit fullscreen mode

Passed!

Alt Text

This is easy one. Maybe you can also have a try at https://bfe.dev

Hope it helps, see you next time.

Top comments (0)