-
Notifications
You must be signed in to change notification settings - Fork 0
/
No_2637.ts
50 lines (39 loc) · 1.35 KB
/
No_2637.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
namespace Leetcode {
type Fn = (...params: any[]) => Promise<any>;
export class No_2637 {
timeLimit(fn: Fn, t: number): Fn {
return async function (...args) {
return Promise.race([fn(...args),
new Promise((_, reject) => {
setTimeout(() => reject("Time Limit Exceeded"), t)
})]);
}
};
}
}
/**
* const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);
* limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms
const fns = fn(...args);
const timeLimitPromise = new Promise((_, reject) => {
setTimeout(() => {
reject("Time Limit Exceeded");
}, t);
});
return Promise.race([fns, timeLimitPromise]);
let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)
myResolve(); // when successful
myReject(); // when error
});
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject('Time Limit Exceeded'); }, t);
fn(...args).then(resolve).catch(reject).finally(() => clearTimeout(timeout));
});
// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
function(value) { code if successful },
function(error) { code if some error }
);
*/