Problem
Given an array functions and a number ms, return a new array of functions.
functionsis an array of functions that return promises.msrepresents the delay duration in milliseconds. It determines the amount of time to wait before resolving or rejecting each promise in the new array.
Each function in the new array should return a promise that resolves or rejects after an additional delay of ms milliseconds, preserving the order of the original functions array.
The delayAll function should ensure that each promise from functions is executed with a delay, forming the new array of functions returning delayed promises.
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Constraints:
functionsis an array of functions that return promises10 <= ms <= 5001 <= functions.length <= 10
Solution
Method 1 – Promise Wrapping with Delay
Intuition
We want to delay the resolution or rejection of each promise returned by the input functions by ms milliseconds. This can be achieved by wrapping each function so that after the original promise settles, we wait for ms ms before resolving or rejecting with the same value.
Approach
- For each function in the input array, create a new function.
- The new function calls the original function to get its promise.
- When the original promise resolves or rejects, set a timeout for
msms, then resolve or reject with the same value. - Return the array of wrapped functions.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n), wherenis the number of functions, since we wrap each function once. - 🧺 Space complexity:
O(n), for the array of wrapped functions.