編寫一個函數(shù)createCounter它掂。它應(yīng)該接受一個初始整數(shù)init。它應(yīng)該返回一個具有三個函數(shù)的對象溯泣。
這三個功能是:
increment()將當(dāng)前值增加1虐秋,然后返回。
遞減()將當(dāng)前值減少1垃沦,然后返回客给。
reset()將當(dāng)前值設(shè)置為init,然后返回肢簿。
Example 1:
Input: init = 5, calls = ["increment","reset","decrement"]
Output: [6,5,4]
Explanation:
const counter = createCounter(5);
counter.increment(); // 6
counter.reset(); // 5
counter.decrement(); // 4
Example 2:
Input: init = 0, calls = ["increment","increment","decrement","reset","reset"]
Output: [1,2,1,0,0]
Explanation:
const counter = createCounter(0);
counter.increment(); // 1
counter.increment(); // 2
counter.decrement(); // 1
counter.reset(); // 0
counter.reset(); // 0
Constraints:
-1000 <= init <= 1000
0 <= calls.length <= 1000
calls[i] is one of "increment", "decrement" and "reset"
解決:
type Counter = {
increment: () => number,
decrement: () => number,
reset: () => number,
}
function createCounter(init: number): Counter {
let count = init;
return {
increment: () => {
return ++init;
},
decrement: () => {
return --init
},
reset: () => {
init = count;
return count
}
}
};
/**
* const counter = createCounter(5)
* counter.increment(); // 6
* counter.reset(); // 5
* counter.decrement(); // 4
*/
/**
https://leetcode.com/problems/counter-ii/solutions/3495319/2665-counter-ii-level-up-your-javascript-skills-with-these-intuitive-implementations/?envType=study-plan-v2&envId=30-days-of-javascript
*/