class RingBuffer[T] {
val array = new Array[T](5)
var count = 0
override def toString: String = array.mkString(",")
def add(value: T): RingBuffer[T] = {
if (count < array.length) {
array(count) = value
} else {
val newIndex = count % array.length
array(newIndex) = value
}
count = count + 1
this
}
}
object RingBuffer {
def apply[T]() = new RingBuffer[T]()
def forInts = apply[Int]()
}
val rb = RingBuffer forInts
rb add 6 //RB = 6,0,0,0,0
rb add 7 //RB = 6,7,0,0,0
rb add 8 //RB = 6,7,8,0,0
rb add 9 //RB = 6,7,8,9,0
rb add 10 //RB = 6,7,8,9,10
rb add 11 //RB = 11,7,8,9,10
rb add 12 //RB = 11,12,8,9,10
rb add 13 //RB = 11,12,13,9,10
rb add 14 //RB = 11,12,13,14,10
rb add 15 //RB = 11,12,13,14,15
Last active
October 29, 2016 01:17
-
-
Save agaro1121/799b2e45299ebbd5de131023f3940c76 to your computer and use it in GitHub Desktop.
Basic Ring Buffer
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment