2637. Promise Time Limit
In this challenge, we create a time-limited version of an asynchronous function that either resolves with the result if it completes in time or rejects if it takes too long.
📄 Problem Statement
Given an asynchronous function fn and a time limit t in milliseconds, return a new time-limited version of the function.
The new function should follow these rules:
- If
fncompletes withintms, it resolves with the result. - If it takes longer, it rejects with the string
"Time Limit Exceeded".
💡 Example
Input:
const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);
limited(150).catch(console.log); // "Time Limit Exceeded"
Output: "Time Limit Exceeded"
🧠 Explanation
We create a wrapper function that runs the original async function in parallel with a timeout Promise. If the timeout hits before fn resolves, we reject. Otherwise, we resolve with fn's result.
This is achieved using Promise.race(), which resolves or rejects as soon as one of the promises settles.
✅ Your Solution
/**
* @param {Function} fn
* @param {number} t
* @return {Function}
*/
var timeLimit = function(fn, t) {
return async function(...args) {
const timeout = new Promise((_, reject) =>
setTimeout(() => reject("Time Limit Exceeded"), t)
);
return Promise.race([fn(...args), timeout]);
};
};