Jeff的隨手筆記

學習當一個前端工程師

0%

用LeetCode寫日記-Day10

今天的問題我覺得是昨天的其餘參數(rest parameter)的延伸問題,在解題中才發現對於其餘參數(rest parameter)跟 擴展運算符(spread operator)有點搞混了。

Day10: Allow One Function Call

問題描述:

Given a function fn, return a new function that is identical to the original function except that it ensures fn is called at most once.

  • The first time the returned function is called, it should return the same result as fn.
  • Every subsequent time it is called, it should return undefined.

問題難度:Easy

問題限制:

  • calls is a valid JSON array
  • 1 <= calls.length <= 10
  • 1 <= calls[i].length <= 100
  • 2 <= JSON.stringify(calls).length <= 1000

我的解題過程

題目的意思應該是要我們寫出一個第一次使用可以執行但再次執行後就無法使用的function。

我的想法是用一個計數器,當為真時可以執行,不為真時就回傳題目要我們回傳的內容,因此:

1
2
3
4
5
6
7
8
9
10
11
12
13
var once = function(fn) {
let count = true
let answer = 0

return function(...args){
if (count) {
answer = fn(args)
return answer
} else {
return undefined
}
}
};

但輸出不是我們想要的:
[{"calls":1,"value":"1,2,3undefinedundefined"},{"calls":2,"value":"2,3,6undefinedundefined"}]

問題一個一個解決
首先我忘記讓count改變,因此新增一行:

1
count = false

然後就是args是一個array,我的寫法等於是把整個array當作一個參數傳遞給 fn function,這跟 fn function預期的不一樣,他預期的應該是單一參數而不是array,因此要把args傳入的參數改成單一參數,因此就要利用擴展運算符(spread operator)來讓array 展開為單個參數。

1
answer = fn(...args)

出來的結果確實是題目所需要的

其他解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function once(fn) {
let hasBeenCalled = false;
let result;

return (...args) => {
if (!hasBeenCalled) {
result = fn(...args);
hasBeenCalled = true;
return result;
} else {
return undefined;
}
};
}

結論

簡單的解說一下:
其餘參數(rest parameter)和擴展運算符(spread operator)雖然都使用了三個點(…)的語法,但它們的作用是不同的。

其餘參數(rest parameter)是函數的一種參數,它可以用來收集函數收到的多餘參數。例如:

1
2
3
4
5
function sum(a, b, ...rest) {
return a + b + rest.reduce((a, b) => a + b, 0);
}

sum(1, 2, 3, 4, 5); // 15

在這種情況下,sum 函數將會收到三個參數,分別是 a、b 和 rest。rest 參數將會包含剩下的所有參數,即 3、4 和 5。

擴展運算符(spread operator)可以用來將數組或對象展開為單個參數。例如:

1
2
3
4
5
6
7
function sum(a, b, c) {
return a + b + c;
}

const numbers = [1, 2, 3];

sum(...numbers); // 6

在這種情況下,sum 函數將會收到三個參數,分別是 numbers 數組中的元素 1、2 和 3。

總結來說,其餘參數是函數的一種參數,它可以用來收集函數收到的多餘參數;擴展運算符可以用來將數組或對象展開為單個參數。