File tree 1 file changed +39
-0
lines changed
1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 2637. Promise Time Limit
2
+ // URL -> https://leetcode.com/problems/promise-time-limit/
3
+
4
+ /**
5
+ * @param {Function } fn
6
+ * @param {number } t
7
+ * @return {Function }
8
+ */
9
+ var timeLimit = function ( fn , t ) {
10
+ return async function ( ...args ) {
11
+ try {
12
+ return new Promise ( ( resolve , reject ) => {
13
+ setTimeout ( ( ) => reject ( "Time Limit Exceeded" ) , t )
14
+ fn ( ...args ) . then ( resolve ) . catch ( reject )
15
+ } )
16
+ } catch ( err ) {
17
+ return err ;
18
+ }
19
+ }
20
+ } ;
21
+
22
+ /**
23
+ * const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);
24
+ * limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms
25
+ */
26
+
27
+ // Alternative Solution
28
+ // return async function (...args) {
29
+ // try {
30
+ // return Promise.race([
31
+ // fn(...args),
32
+ // new Promise((_, re) => {
33
+ // setTimeout(() => re("Time Limit Exceeded"), t)
34
+ // })
35
+ // ])
36
+ // } catch (err) {
37
+ // return err;
38
+ // }
39
+ // }
You can’t perform that action at this time.
0 commit comments