public
Created

SlidingWindowMap

  • Download Gist
SlidingWindowMap.scala
Scala
1 2 3 4 5 6 7 8 9 10 11
class SlidingWindowMap(keys: Set[String], maxCount: Int, periodMs: Int) {
val times = collection.mutable.Map(keys.map(k => (k, Vector[Long]())).toList:_*)
def nextKey: Option[String] = {
val now = System.currentTimeMillis
this.synchronized {
val key = times.find(_._2.dropWhile(_ < now - periodMs).size < maxCount).map(_._1)
key.foreach { k => times(k) = times(k).dropWhile(_ < now - periodMs) :+ now }
key
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.