2025-08-21 14:30:46 +0300 MSK

Counter II

Code

class Counter {
    constructor(init) {
        this.init = init;
        this.val = init;
    }
    increment() {
        let val = this.val + 1;
        this.val = val;
        return val;
    }
    decrement() {
        let val = this.val - 1;
        this.val = val;
        return val;
    }
    reset() {
        let val = this.init;
        this.val = val;
        return val;
    }
}

/**
 * @param {integer} init
 * @return { increment: Function, decrement: Function, reset: Function }
 */
var createCounter = function(init) {
    return new Counter(init)
};

/**
 * const counter = createCounter(5)
 * counter.increment(); // 6
 * counter.reset(); // 5
 * counter.decrement(); // 4
 */