js EAsy
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem is to implement a function similar to Promise.all in JavaScript, which reso
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to implement a function similar to Promise.all in JavaScript, which resolves an array of promises concurrently and returns their results in the same order. The first step in understanding the solution is recognizing that:\n\nAll promises need to be resolved in parallel.\nResults must be collected in the same order as the input functions.\nIf any promise fails, the entire operation should reject immediately.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate a new Promise that resolves when all input promises resolve or rejects when any one of them fails.\nUse a results array to store the resolved values at their respective indices.\nUse a completed counter to track how many promises have resolved successfully.\nIterate through the array of functions, execute each one, and handle its resolution or rejection.\nResolve the Promise with the results array once all promises are resolved.\nReject the Promise immediately if any promise fails.\nComplexity\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```javascript []\n/**\n * @param {Array<Function>} functions\n * @return {Promise<any[]>}\n */\nvar promiseAll = async function(functions) {\n    return new Promise((resolve, reject) => {\n        const results = [];\n        let completed = 0;\n\n        if (functions.length === 0) {\n            resolve(results); // If no functions, resolve with an empty array.\n        }\n\n        functions.forEach((fn, index) => {\n            fn()\n                .then(value => {\n                    results[index] = value; // Store results in the same order.\n                    completed++;\n\n                    if (completed === functions.length) {\n                        resolve(results); // Resolve when all are done.\n                    }\n                })\n                .catch(error => {\n                    reject(error); // Reject immediately on any failure.\n                });\n        });\n    });\n};\n\n/**\n * Example usage:\n * const promise = promiseAll([() => new Promise(res => res(42)), () => new Promise(res => res(84))]);\n * promise.then(console.log); // [42, 84]\n */\n\n```
['JavaScript']