-
Notifications
You must be signed in to change notification settings - Fork 0
/
promiseTimelimit.ts
36 lines (29 loc) · 1.12 KB
/
promiseTimelimit.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
Given an asynchronous function fn and a time t in milliseconds, return a new time limited version of the input function. fn takes arguments provided to the time limited function.
The time limited function should follow these rules:
If the fn completes within the time limit of t milliseconds, the time limited function should resolve with the result.
If the execution of the fn exceeds the time limit, the time limited function should reject with the string "Time Limit Exceeded".
*/
type Fn = (...params: any[]) => Promise<any>;
function timeLimit(fn: Fn, t: number): Fn {
return async function (...args) {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject('Time Limit Exceeded');
}, t);
return fn(...args)
.then((res) => {
clearTimeout(timeout);
resolve(res);
})
.catch((err) => {
clearTimeout(timeout);
reject(err);
});
});
};
}
/**
* const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);
* limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms
*/