DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 49

The task is to implement flattenThunk to chain functions together.

The boilerplate code

function flattenThunk(thunk) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

A thunk is a function that takes a callback. Thunks can nest, which means the callback can return another thunk. The goal of the flattenThunk is to chain and flatten these nested thunks so they behave like one flat thunk.

The function returns a new thunk. If an error occurs at any level, it stops and passes the error up.

return function (callback) {
function handle(err, result) {
if(err) return callback(err)
}
}
Enter fullscreen mode Exit fullscreen mode

When the function is called, it passes a recursive helper as the callback. Each time a thunk returns another thunk, the helper calls it again.

if(typeof result === 'function') {
result(handle)
} else {
callback(err, result)
}
Enter fullscreen mode Exit fullscreen mode

When a final value is reached, it calls the original callback with undefined as error and the result as the second argument.

The final code

function flattenThunk(thunk) {
  // your code here
  return function (callback) {
    function handle (err, result) {
      if(err) return callback(err)
      if(typeof result === 'function') {
        result(handle)
      } else {
        callback(undefined, result)
      }
    }
    thunk(handle)
  }
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)