2637. Promise Time Limit

Given an asyncronous function fn and a time t in milliseconds, return a new time limited version of the input function.

A time limited function is a function that is identical to the original unless it takes longer than t milliseconds to fullfill. In that case, it will reject with “Time Limit Exceeded”. Note that it should reject with a string, not an Error.

 

Example 1:

Example 2:

Example 3:

Example 4:

Constraints:

  • 0 <= inputs.length <= 10
  • 0 <= t <= 1000
  • fn returns a promise

From: LeetCode
Link: 2637. Promise Time Limit


Solution:

Ideas:
The code is to create a new function that is identical to the original function, except that it will reject with a string “Time Limit Exceeded” if it takes longer than t milliseconds to fulfill.
The code works by first creating a new promise that will resolve after t milliseconds. This promise is then used to create a new function that calls the original function and then waits for either the original function to resolve or the timeout promise to resolve. If the original function resolves first, then the new function returns the value from the original function. If the timeout promise resolves first, then the new function rejects with the string “Time Limit Exceeded”.
Code:
/**
 * @param {Function} fn
 * @param {number} t
 * @return {Function}
 */
var timeLimit = function(fn, t) {
	return async function(...args) {
        // Create a new promise that will resolve after t milliseconds.
        const timeoutPromise = new Promise((resolve, reject) => {
            setTimeout(() => reject("Time Limit Exceeded"), t);
        });
        // Wait for either the original function to resolve or the timeout promise to resolve.
        return await Promise.race([fn(...args), timeoutPromise]);
    };
};

/**
 * const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);
 * limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms
 */
05-16 10:31