This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan
The task is to implement flattenThunk to chain functions together.
The boilerplate code
function flattenThunk(thunk) {
// your code here
}
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)
}
}
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)
}
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)
}
}
That's all folks!
This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan
Bukunmi Odugbesan | Sciencx (2025-11-08T22:44:35+00:00) Coding Challenge Practice – Question 49. Retrieved from https://www.scien.cx/2025/11/08/coding-challenge-practice-question-49/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.