编写一个函数createCounter。它应该接受一个初始整数init。它应该返回一个具有三个函数的对象。
这三个功能是:
increment()将当前值增加1,然后返回。
递减()将当前值减少1,然后返回。
reset()将当前值设置为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
*/
网友评论