All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g2601_2700.s2637_promise_time_limit.solution.ts Maven / Gradle / Ivy

There is a newer version: 1.35
Show newest version
// #Medium #2023_09_01_Time_57_ms_(84.99%)_Space_43_MB_(45.71%)

type Fn = (...params: any[]) => Promise

function timeLimit(fn: Fn, t: number): Fn {
    return async function (...args) {
        const timeout = new Promise((_, reject) => {
            setTimeout(() => {
                reject('Time Limit Exceeded') //NOSONAR
            }, t)
        })
        return Promise.race([fn(...args), timeout])
    }
}

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

export { timeLimit }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy