Recent Posts
Recent Comments
게으른개발너D
[Function, Closure, Class] Counter II (closure 함수 여러개 넣기) ⭐️ 본문
https://leetcode.com/problems/counter-ii/description/
Write a function createCounter. It should accept an initial integer init. It should return an object with three functions.
The three functions are:
- increment() increases the current value by 1 and then returns it.
- decrement() reduces the current value by 1 and then returns it.
- reset() sets the current value to init and then returns it.
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
- total calls not to exceed 1000
solution
/**
* @param {integer} init
* @return { increment: Function, decrement: Function, reset: Function }
*/
var createCounter = function(init) {
let num = init;
const initial = init;
const increment = () => {
num++;
return num;
}
const decrement = () => {
num--;
return num;
}
const reset = () => {
num = initial;
return num;
}
return { increment, decrement, reset };
};
/**
* const counter = createCounter(5)
* counter.increment(); // 6
* counter.reset(); // 5
* counter.decrement(); // 4
*/
solution2
traditional function 사용
var createCounter = function(init) {
let presentCount = init;
function increment() {
return ++presentCount;
}
function decrement() {
return --presentCount;
}
function reset() {
return (presentCount = init);
}
return { increment, decrement, reset };
};
solution3
arrow function 사용
var createCounter = function(init) {
let presentCount = init
return {
increment: () => ++presentCount,
decrement: () => --presentCount,
reset: () => presentCount = init,
}
};
solution4
class 사용
class Counter {
constructor(init) {
this.init = init;
this.presentCount = init;
}
increment() {
this.presentCount += 1;
return this.presentCount;
}
decrement() {
this.presentCount -= 1;
return this.presentCount;
}
reset() {
this.presentCount = this.init;
return this.presentCount;
}
}
var createCounter = function(init) {
return new Counter(init);
};
'알고리즘 > 과제' 카테고리의 다른 글
[Array] Array Wrapper (method, prototype 만들기) ⭐️ (0) | 2023.07.04 |
---|---|
[Function, Closure] Allow One Function Call (함수 한 번만 호출하기) (0) | 2023.07.03 |
[Generator] Generate Fibonacci Sequence ⭐️ (0) | 2023.07.03 |
[Promise] Promise Time Limit (feat. race) ⭐️ (0) | 2023.07.03 |
[Array] Apply Transform Over Each Element in Array (map 구현하기) (0) | 2023.07.03 |
Comments