This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for JavaScript Coding Question on BFE.dev
31. implement async helper - `race()`

One possible solution:

const race = (asyncFuncArr) => {
  return (callback, data) => {
    let done = false;
    let numComplete = 0;

    for (let i = 0; i < asyncFuncArr.length; i++) {
      const asyncFunc = asyncFuncArr[i];
      asyncFunc((error, result) => {
        if (!done) {
          numComplete++;
          if (error) {
            done = true;
            callback(error);
          } else {
            done = true;
            callback(undefined, result);
          }
        }
      }, data);
    }
  };
};

Explanation:

  • The race() function takes an array of async functions as input and returns a new function with a callback that should be called when any async function is done.
  • The new function loops through the async functions and calls them with the provided data.
  • Each async function is passed a callback function that checks if the race has finished yet. If it has not finished yet, it increments the numComplete variable and checks if the async function produced an error. If it has produced an error, it calls the main callback with the error. Otherwise, it calls the main callback with the data.
  • If a race has already finished, no more async functions are called.