Skip to content

Instantly share code, notes, and snippets.

@johnynek
Forked from anonymous/summingbuffer.scala
Created December 20, 2012 20:54
Show Gist options
  • Save johnynek/4348475 to your computer and use it in GitHub Desktop.
Save johnynek/4348475 to your computer and use it in GitHub Desktop.
// Adds an item to the buffer and returns None, or fills the buffer and returns the sum
@tailrec
final def offer(item: V, acc: Option[V] = None): Option[V] =
if(!queue.offer(item)) {
// Queue is full
val toSum = ListBuffer[V]()
queue.drainTo(toSum.asJava)
// Add everything up and get the new acc:
val newAcc = Monoid.plus(acc, Some(Monoid.sum(toSum)))
// We never actually got the item in:
offer(item, newAcc)
}
else {
// We added, so just return the accumulator
acc
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment