JavaScript promiseAll Solution
Intuition\nHere\'s the intuition in two concise points:\n\n1. Parallel Execution and Order Preservation: We execute all asynchronous functions simultaneously an
# Intuition\nHere\'s the intuition in two concise points:\n\n1. **Parallel Execution and Order Preservation**: We execute all asynchronous functions simultaneously and store their results in an array at the corresponding index to maintain the original order, even though they resolve at different times.\n\n2. **Immediate Rejection Handling**: If any promise rejects, we immediately reject the main promise with the first encountered error, mimicking `Promise.all` behavior where the overall operation fails as soon as any individual promise fails.\n\n# Approach\n1. A new Promise is created and will resolve or reject based on the behavior of the provided asynchronous functions.\n2. We keep track of results in the results array and the number of completed promises with the completed variable.\n3. We iterate over each function in the functions array, executing them in parallel.\n4. Each function\'s result is stored in the results array at the correct index.\n5. If a function resolves, it increments the completed count. When all functions are resolved, resolve(results) is called.\n6. If any function rejects, the promise is immediately rejected with the error of the first rejection.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {Array<Function>} functions\n * @return {Promise<any>}\n */\nvar promiseAll = function(functions) {\n    return new Promise((resolve, reject) => {\n        const results = [];\n        let completed = 0;\n\n        functions.forEach((fn, index) => {\n            fn()\n                .then((result) => {\n                    results[index] = result;\n                    completed += 1;\n                    if (completed === functions.length) {\n                        resolve(results);\n                    }\n                })\n                .catch((error) => {\n                    reject(error);\n                });\n        });\n    });\n};\n\n// Example usage:\nconst asyncFunction1 = () => new Promise((resolve) => setTimeout(() => resolve(1), 100));\nconst asyncFunction2 = () => new Promise((resolve) => setTimeout(() => resolve(2), 200));\nconst asyncFunction3 = () => new Promise((resolve) => setTimeout(() => resolve(3), 300));\n\npromiseAll([asyncFunction1, asyncFunction2, asyncFunction3])\n    .then((results) => console.log(results)) // [1, 2, 3]\n    .catch((error) => console.log(error));\n\n\n/**\n * const promise = promiseAll([() => new Promise(res => res(42))])\n * promise.then(console.log); // [42]\n */\n```
['JavaScript']