Delay the Resolution of Each Promise Problem
Description
LeetCode Problem 2821.
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.
Example 1:
Input:
functions = [
() => new Promise((resolve) => setTimeout(resolve, 30))
],
ms = 50
Output: [80]
Explanation: The promise from the array would have resolved after 30 ms, but it was delayed by 50 ms, thus 30 ms + 50 ms = 80 ms.
Example 2:
Input:
functions = [
() => new Promise((resolve) => setTimeout(resolve, 50)),
() => new Promise((resolve) => setTimeout(resolve, 80))
],
ms = 70
Output: [120,150]
Explanation: The promises from the array would have resolved after 50 ms and 80 ms, but they were delayed by 70 ms, thus 50 ms + 70 ms = 120 ms and 80 ms + 70 ms = 150 ms.
Example 3:
Input:
functions = [
() => new Promise((resolve, reject) => setTimeout(reject, 20)),
() => new Promise((resolve, reject) => setTimeout(reject, 100))
],
ms = 30
Output: [50,130]
Constraints:
functionsis an array of functions that return promises10 <= ms <= 5001 <= functions.length <= 10
Solution
Approach: Wrap each function with a leading delay
We return one new function per original function. The new function waits ms milliseconds and only then calls the original, so the original promise starts late and finishes ms later than it normally would.
mapoverfunctions, keeping the order.- Inside an
asyncwrapper,awaita promise that resolves aftersetTimeout(..., ms), thenreturn fn(). - Returning the inner promise from an
asyncfunction adopts its outcome, so a rejection stays a rejection and the extra delay is the same either way.
Example 3 shows it: the rejections happen after 20 and 100 ms plus the 30 ms wait, giving 50 and 130.
Complexity: Time O(n) to build the array, space O(n).
/**
* @param {Array<Function>} functions
* @param {number} ms
* @return {Array<Function>}
*/
var delayAll = function (functions, ms) {
return functions.map(fn => async () => {
await new Promise(resolve => setTimeout(resolve, ms));
return fn();
});
};