/* CookieJar ADT, Mutable Object-Oriented Version
   Using Scala Lists of Pairs (CookieJarArrayBuffer)
   CSci 556: Multiparadigm Programming, Spring 2012
   CSci 555: Functional Programming, Spring 2016
   H. Conrad Cunningham, Professor
   Computer and Information Science
   University of Mississippi

1234567890123456789012345678901234567890123456789012345678901234567890

2010-Spring: Developed from mutable Ruby version
2012-Spring: Minor updates
2016-03-09:  Some cleanup of Scala code and comments
2022-04-18:  Scala 3 compatibility check, added Unit to procedures

*/

import scala.collection.mutable.ArrayBuffer

/* Class CookieJarArrayBuffer implements the CookieJar ADT using
   Scala's ArrayBuffer data structure to implement the jar
   (mathematical bag) of cookies.  The cookies occur in the
   Arraybuffer the same number of times they do in the cookie
   jar.

   IMPLEMENTATION INVARIANT: 
     (ForAll c : c IN CookieType ::
                 OCCURRENCES(c,Bag) == jar.filter(_==c).length )
*/

class CookieJarArrayBuffer[CookieType]
      extends CookieJar[CookieType] {

  // CookieJar's bag model is implemented by ArrayBuffer jar.
  private var jar = new ArrayBuffer[CookieType]
 
  def putIn(cookie: CookieType): Unit = { jar += cookie }
 
  def eat(cookie: CookieType): Unit = {
    val in = jar.indexOf(cookie) 
    if (in >= 0)
      jar.remove(in)
    else 
      sys.error("Attempt to eat cookie \"" + cookie +
                "\", which is not in the jar.")
  }
       
  def isEmpty: Boolean                 = jar.isEmpty

  def has(cookie: CookieType): Boolean = jar.contains(cookie)

  /* Redefine toString to return form "CookieJar(e1,e2,e3,...,en)"
     with all elements of bag in arbitrary order.
   */

  override def toString = "CookieJar(" + jar.mkString(",") + ")"

}

