Problem Description
Given an array of functions (each returning a promise) and a delay in milliseconds (ms), return a new array of functions. When invoked, each new function will execute the original promise-returning function and then delay its resolution or rejection by an additional ms milliseconds. For example, if the original function’s promise resolves after 30 ms and ms = 50, the new promise resolves after 80 ms (30 + 50).
Key Insights
- Each function in the new array wraps the original function, adding an extra delay after its promise settles.
- The additional delay is applied uniformly whether the promise resolves or rejects.
- The order of promises is preserved, and there is no dependency between them.
- A helper delay function (or equivalent) is used to wait for ms milliseconds before forwarding the result or error.
Space and Time Complexity
Time Complexity: O(n) because we process each of the n functions to wrap them. Space Complexity: O(n) for storing the new array of delayed functions.
Solution
The solution involves iterating over the input array and creating a wrapper function for each original function. When the wrapper is called, it:
- Executes the original function to get its promise.
- Waits for the original promise to settle (either resolve or reject).
- Uses an additional delay (via a helper delay function) to postpone the final resolution or rejection by ms milliseconds. The key challenge is to correctly chain the original promise with the delay, handling both success and error cases uniformly.
Code Solutions
Below are implementations in Python, JavaScript, C++, and Java.