-
Notifications
You must be signed in to change notification settings - Fork 0
/
promiseTimeLimit.js
105 lines (89 loc) · 2.79 KB
/
promiseTimeLimit.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
https://leetcode.com/problems/promise-time-limit/description/?envType=study-plan-v2&envId=30-days-of-javascript
2637. Promise Time Limit
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".
Example 1:
Input:
fn = async (n) => {
await new Promise(res => setTimeout(res, 100));
return n * n;
}
inputs = [5]
t = 50
Output: { "rejected": "Time Limit Exceeded", "time": 50 }
Explanation:
const limited = timeLimit(fn, t)
const start = performance.now()
let result;
try {
const res = await limited(...inputs)
result = { "resolved": res, "time": Math.floor(performance.now() - start) };
} catch (err) {
result = { "rejected": err, "time": Math.floor(performance.now() - start) };
}
console.log(result) // Output
The provided function is set to resolve after 100ms.However, the time limit is set to 50ms.It rejects at t = 50ms because the time limit was reached.
Example 2:
Input:
fn = async (n) => {
await new Promise(res => setTimeout(res, 100));
return n * n;
}
inputs = [5]
t = 150
Output: { "resolved": 25, "time": 100 }
Explanation:
The function resolved 5 * 5 = 25 at t = 100ms.The time limit is never reached.
Example 3:
Input:
fn = async (a, b) => {
await new Promise(res => setTimeout(res, 120));
return a + b;
}
inputs = [5, 10]
t = 150
Output: { "resolved": 15, "time": 120 }
Explanation:
The function resolved 5 + 10 = 15 at t = 120ms.The time limit is never reached.
Example 4:
Input:
fn = async () => {
throw "Error";
}
inputs = []
t = 1000
Output: { "rejected": "Error", "time": 0 }
Explanation:
The function immediately throws an error.
*/
/**
* @param {Function} fn
* @param {number} t
* @return {Function}
*/
var timeLimit = function(fn, t) {
return function(...args) {
return new Promise(function(resolve, reject) {
const timer = setTimeout(() => {
clearTimeout(timer);
reject("Time Limit Exceeded");
}, t);
fn(...args)
.then((res) => {
clearTimeout(timer);
resolve(res);
})
.catch(e => {
clearTimeout(timer);
reject(e);
})
});
}
};
/**
* const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);
* limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms
*/