Jeff的隨手筆記

學習當一個前端工程師

0%

用LeetCode寫日記-Day16

多花了一點時間,一開始有被題目嚇到。

Day16: 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".

問題難度:Medium

問題限制:

  • 0 <= inputs.length <= 10
  • 0 <= t <= 1000
  • fn returns a promise

我的解題過程:

之前有寫過基礎的問題,如promise、setTimeout、clearTimeout。

這題感覺時把所有的問題整合,當下看到有點不知所措,但一步步拆解後就又好像不難。

首先題目有說到如果成功要….失敗要…

看起來就很像promise的寫法,因此先創立一個promise

1
return new Promise((resolve, reject) => {code})

接下來要來處理code的部分,根據題目的需求我們設置一個setTimeout,並且要包含clearTimeout:

1
2
3
4
const timeoutId = setTimeout(() => {
clearTimeout(timeoutId);
reject("Time Limit Exceeded");
}, t);

接下來就是讓fn執行這個setTimeout了

1
2
3
4
5
6
7
8
fn(...args)
.then((res) => {
clearTimeout(timeoutId);
resolve(res);
})
.catch((error) => {
reject(error);
});

這邊在一開始我犯了個錯誤,並沒有使用,想說之前已經把所有參數傳入args了,但第一次使用 ...args 是為了接收所有傳入 timeLimit 的參數,而第二次使用 ...args 則是為了將這些參數傳遞給 **fn**。

完整code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var timeLimit = function (fn, t) {
return async function (...args) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
clearTimeout(timeoutId);
reject("Time Limit Exceeded");
}, t);

fn(...args)
.then((res) => {
clearTimeout(timeoutId);
resolve(res);
})
.catch((error) => {
reject(error);
});
});
};
};;

其他code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var timeLimit = function(fn, t) {
return async function(...args) {
const originalFnPromise = fn(...args);

const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => {
reject('Time Limit Exceeded')
}, t);
})

return Promise.race([originalFnPromise, timeoutPromise]);
}
};

總結

看到問題時真的不能緊張,仔細觀察題目。基本上以我目前的能力所有的解答方式我都有學過了,只要靜下心來一定有辦法解開(拼時間的還不行,現階段能解出來就要偷笑了)。