Source: lib/CounterMulti.js

const { hasProp } = require('sesajstools')

/**
 * Une série de compteurs, chaque clé étant un compteur pouvant être incrémenté, décrémenté ou supprimé
 * @constructor
 */
function CounterMulti () {
  /**
   * Le nombre de clés
   * @type {number}
   */
  this.length = 0
}

/**
 * Incrémente une clé (la créé si elle n'existait pas)
 * @param key
 */
CounterMulti.prototype.inc = function (key) {
  if (hasProp(this, key)) this[key]++
  else {
    this[key] = 1
    this.length++
  }
}

/**
 * Décrémente une clé (et la crée si elle n'existait pas)
 * @param key
 */
CounterMulti.prototype.dec = function (key) {
  if (hasProp(this, key)) this[key]--
  else {
    this[key] = -1
    this.length++
  }
}

/**
 * Efface une clé
 * @param key
 */
CounterMulti.prototype.delete = function (key) {
  if (hasProp(this, key)) delete this[key]
  this.length--
}

/**
 * Renvoie le total de tous les compteurs
 * @returns {number}
 */
CounterMulti.prototype.total = function () {
  let total = 0
  for (const key in this) {
    if (hasProp(this, key) && key !== 'length') total += this[key]
  }
  return total
}

/**
 * Recalcule la propriété length (si on a ajouté des propriétés manuellement)
 * @returns {number}
 */
CounterMulti.prototype.resetLength = function () {
  this.length = Object.keys(this).length - 1
  return this.length
}

module.exports = CounterMulti