g2601_2700.s2637_promise_time_limit.solution.ts Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
// #Easy #Medium #2023_08_31_Time_53_ms_(93.41%)_Space_42.7_MB_(62.71%)
type Fn = (...params: any[]) => Promise
function timeLimit(fn: Fn, t: number): Fn {
return async function (...args: any[]): Promise {
const fns = fn(...args)
const timeLimitPromise = new Promise((_, reject) => {
setTimeout(() => {
reject(new Error('Time Limit Exceeded'))
}, t)
})
return Promise.race([fns, timeLimitPromise])
}
}
/*
* const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);
* limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms
*/
export { timeLimit }