2721. Execute Anonymous Functions in Parallel Solution
Intuition\n Describe your first thoughts on how to solve this problem. \nReturn a new Promise that checks if the input array Is empty. Create an array (results)
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nReturn a new Promise that checks if the input array Is empty. Create an array (results) to store the results of each function. Then use a counter to store track of completed functions. Then, iterate over each function array. Call each function either updating the results array and incrementing the completed functions count or reject the promise with that error.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nReturn a new Promise. Inside the Promise, we check if the input array is empty. If so, immidately resolve with an empty array. WE then create a array (results) to store the results of each function. We create another variable (completedCount) to keep track of how many functions have completed. We itreate over each function using forEach() method. Calling each function and attaching .then() and .catch() handlers depending on the outcome. In the .then() handler, we store the result un the (results) array, increment the (completedCount), and resolve the ,ain promise once all functions have completed. If any function rejects, we reject the main promise with that error.\n\n# Complexity\n- Time complexity: Linear 0(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\npromiseAll has Linear O(n) time complexity where (n) is the number of functions. The actual time taken depends on the execution of the slowest function.\n\n- Space complexity: Linear 0(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nWe create an array (results) to store all the function results, giving linear O(n) space complexity.\n\n# Code\n```\n/**\n * @param {Array<Function>} functions\n * @return {Promise<any>}\n */\nvar promiseAll = function(functions) {\n    return new Promise((resolve, reject) => {\n        if (functions.length === 0) {\n            resolve([]);\n            return;\n        }\n\n        const results = new Array(functions.length);\n        let completedCount = 0;\n\n        functions.forEach((fn, index) => {\n            fn()\n            .then(result => {\n                results[index] = result;\n                completedCount++;\n\n                if (completedCount === functions.length) {\n                    resolve(results);\n                }\n            })\n            .catch(reject);\n        });\n    });\n};\n\n/**\n * const promise = promiseAll([() => new Promise(res => res(42))])\n * promise.then(console.log); // [42]\n */\n```
['JavaScript']