Topic Description

Imagine you are developing a feature that needs to track various metrics. We need a flexible way to manage counters in the code. Your task is to design a function named createCounter that can be used to generate customizable counters with specific initial values.

createCounter will return an object with the following methods:

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

Answer

function createCounter(initialValue = 0) {
  let value = initialValue 

  function get() {
    return value
  }

  function increment() {
    value += 1 
    return value 
  }

  function decrement() {
    value -= 1 
    return value
  }

  function reset() {
    value = initialValue
    return value
  }

  return {
    get, 
    increment,
    decrement,
    reset
  }
}
function Counter(){
	this.value = initNum
	this.initValue = initNum
}
	
Counter.prototype.get = function(){
	return this.value
}

Counter.prototype.increment = function(){
	this.value+=1
	return this.value
}

Counter.prototype.decrement = function(){
	this.value-=1
	return this.value
}

Counter.prototype.reset = function(){
	this.value = this.initValue
	return this.value
}
	
function createCounter(initNum = 0){	
	return new Counter(initNum);
}
class Counter {
  constructor(initialValue = 0) {
    this.initialValue = initialValue;
    this.value = initialValue;
  }
  get() {
    return this.value;
  }
  increment() {
		this.value += 1;
    return this.value;
  }
  decrement() {
		this.value -= 1
    return this.value;
  }
  reset() {
    this.value = this.initialValue;
    return this.value;
  }
}

function makeCounter(initialValue = 0) {
  return new Counter(initialValue);
}