Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New counter #10

Open
pathikrit opened this issue Mar 9, 2016 · 0 comments
Open

New counter #10

pathikrit opened this issue Mar 9, 2016 · 0 comments

Comments

@pathikrit
Copy link
Owner

import scala.collection.mutable

class Counter[A](allowNegativeCount: Boolean) extends mutable.Map[A, Int] {
  private[this] val counter = mutable.Map.empty[A, Int] withDefaultValue 0

  def +=(key: A): this.type = this += (key -> 1)

  override def -=(key: A) = this += (key -> -1)

  def ++=(xs: TraversableOnce[A]): this.type = {
    xs foreach +=
    this
  }

  override def +=(kv: (A, Int)) = {
    val (k, v) = kv
    counter(k) += v
    if (counter(k) == 0 || (!allowNegativeCount && counter(k) < 0)) counter.remove(k)
    this
  }

  override def get(key: A) = counter.get(key)

  override def iterator = counter.iterator
}

object Counter {
  def empty[A](allowNegativeCount: Boolean): Counter[A] = new Counter[A](allowNegativeCount)
  def apply[A](xs: TraversableOnce[A], allowNegativeCount: Boolean): Counter[A] = empty[A](allowNegativeCount) ++= xs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant