문제
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.
예제
counter 변수는 increment, decrement, reset 함수들이 들어있는 객체를 반환하는데, 각 함수를 실행시킬 때마다 counter 내에 있는 값이 함수 기능에 의해 계산된 뒤 반환됨.
counter 내부의 값은 보존되기 때문에, 증가하는 함수인 increment()를 여러 번 호출할 시 내부 값이 해당 횟수만큼 오르는 모습을 확인할 수 있음.
코드
/**
* @param {integer} init
* @return { increment: Function, decrement: Function, reset: Function }
*/
var createCounter = function(init) {
let counter = init;
return {
increment() {
counter += 1;
return counter;
},
decrement() {
counter -= 1;
return counter;
},
reset() {
counter = init;
return counter;
}
}
};
/**
* const counter = createCounter(5)
* counter.increment(); // 6
* counter.reset(); // 5
* counter.decrement(); // 4
*/
함수 createCounter의 반환값은 3개의 함수가 들어있는 객체가 된다.
1. increment() : counter 값을 1 증가시킨다.
2. decrement() : counter 값을 1 감소시킨다.
3. reset() : counter 값을 init으로 초기화시킨다.
'Algorithm' 카테고리의 다른 글
[LeetCode] 2667. Create Hello World Function (0) | 2024.01.29 |
---|---|
[LeetCode] 2666. Allow One Function Call (0) | 2024.01.26 |
[LeetCode] 2648. Generate Fibonacci Sequence (0) | 2024.01.24 |
[LeetCode] 2635. Apply Transform Over Each Element in Array (0) | 2024.01.23 |
[LeetCode] 2634. Filter Elements from Array (0) | 2024.01.22 |