문제

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

+ Recent posts