Coding Challenge Practice - Question 91

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MyrinNew
    Senior Member
    • Feb 2024
    • 5168

    #1

    Coding Challenge Practice - Question 91

    The task is to implement the async function helper parallel()


    The boilerplate code






    function parallel(funcs){
    // your code here
    }







    The parallel function is supposed to accept an array of async functions, run all the functions at the same time, with each function having the form func(callback).


    If there are no functions






    if (funcs.length === 0) {
    callback(undefined, []);
    return;
    }







    Store the outputs by index, count the finished tasks and ensure the callback fires only once






    const results = [];
    let completed = 0;
    let hasError = false;







    To run all the functions in parallel






    funcs.forEach((func, index) => {
    func((error, result) => {







    To prevent multiple callbacks






    if (hasError) return;







    To handle errors






    if (error) {
    hasError = true;
    callback(error, undefined);
    return;
    }







    To preserve the order even if tasks finish out of order






    results[index] = result;







    The callback should be called when all the tasks are completed






    completed++;

    if (completed === funcs.length) {
    callback(undefined, results);
    }







    The final code






    function parallel(funcs){
    // your code here
    return function (callback) {
    if(funcs.length === 0) {
    callback(undefined, []);
    return;
    }

    const results = [];
    let completed = 0;
    let hasError = false;

    funcs.forEach((func, index) => {
    func((error, result) => {
    if(hasError) return;

    if(error) {
    hasError = true;
    callback(error, undefined);
    return;
    }
    results[index] = result;
    completed++;

    if (completed === funcs.length) {
    callback(undefined, results)
    }
    })
    })
    }
    }







    That's all folks!




    More...
Working...