Define a private counter that increments and decrements.

by Ansmtz

JavaScript

const privateCounter = () => {
  let i = 0
  return {
    incr: () => {
      i += 1
    },
    decr: () => {
      i -= 1
    },
    getValue: () => {
      return i
    }
  }
}

const counterOne = privateCounter()
counterOne.incr()
counterOne.incr()
console.log(counterOne.getValue())
const counterTwo = privateCounter()
counterTwo.incr()
counterTwo.decr()
counterTwo.decr()
console.log(counterOne.getValue())
console.log(counterTwo.getValue())