문제
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.
https://leetcode.com/problems/counter-ii/
예시
코드
/**
* @param {integer} init
* @return { increment: Function, decrement: Function, reset: Function }
*/
var createCounter = function(init) {
let value = init;
const counter = {
increment() {
return value += 1;
},
decrement(){
return value -= 1;
},
reset(){
return value = init;
}
}
return counter;
};
/**
* const counter = createCounter(5)
* counter.increment(); // 6
* counter.reset(); // 5
* counter.decrement(); // 4
*/
createCounter가 counter 객체를 리턴하도록 하였다. counter 객체는 increment(), reset(), decrement() 메소드를 갖고 있으며, 인자로 들어온 초기값에 대해 각각 +1, init, -1 값을 리턴한다.
728x90
'Algorithm > leetcode' 카테고리의 다른 글
[leetcode][JS] 2667. Create Hello World Function (0) | 2024.01.29 |
---|---|
[leetcode][JS] 2666. Allow One Function Call (0) | 2024.01.26 |
[leetcode][JS] 2648. Generate Fibonacci Sequence (0) | 2024.01.25 |
[leetcode][JS] 2635. Apply Transform Over Each Element in Array (0) | 2024.01.23 |
[leetcode][JS] 2634. Filter Elements from Array (0) | 2024.01.22 |