Skip to content

Instantly share code, notes, and snippets.

@hohonuuli
Last active December 19, 2017 23:39
Show Gist options
  • Select an option

  • Save hohonuuli/b005eae129b8b299a9d88b5047a6f656 to your computer and use it in GitHub Desktop.

Select an option

Save hohonuuli/b005eae129b8b299a9d88b5047a6f656 to your computer and use it in GitHub Desktop.
Scala class for Medium article
import java.time.Instant
import scala.collection.mutable
import scilube.Matlib
class BudgetTimeSeries {
private[this] val series = new mutable.TreeMap[Instant, Double]
def addToSeries(events: Seq[Transaction]): Unit = {
events.foreach(e => {
val t = e.date
val v = e.value
series.get(t) match {
case None => series.put(t, v)
case Some(c) => series.put(t, c + v)
}
})
}
def raw: Seq[(Instant, Double)] = series.toSeq.sortBy(_._1)
def cumulative(): Seq[(Instant, Double)] = {
val cs = Matlib.cumsum(series.values.toArray)
series.keys.zip(cs).toSeq.sortBy(_._1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment