package pl.edu.pw.mini.sg.util

import scala.collection.mutable.Buffer




final class RangedCache[T](constructor: Int => T) {
  val buffer = Buffer[T](constructor(0))
  var zeroPos = 0


  def growForParam(param: Int) : Unit =
    if (zeroPos+param < 0) {
      Range(param, -zeroPos).map(constructor) ++=: buffer
      zeroPos = -param
    } else if (zeroPos+param >= buffer.size) {
      buffer ++= Range.inclusive(buffer.size-zeroPos, param).map(constructor)
    } else {
      // We arleady contain required element
      Unit
    }

  def get(param: Int) : T = {
    growForParam(param)
    buffer(param+zeroPos)
  }
}
