Created
August 20, 2025 03:48
-
-
Save michbarsinai/539e84f720aeac7bd2f24df61118694d to your computer and use it in GitHub Desktop.
Scala interactive script for restaurant meal price estimaton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Example usage | |
| > scala | |
| :load estimation.scala | |
| meal add i("Burger", 19.0, 3) | |
| meal add i("Burger (v)", 19.0, 1) | |
| meal add i("Salad", 12.22, 4) | |
| ll // prints meal, counts, item indices | |
| setCount(2, 3) // add 3 salads, not 4 | |
| ll | |
| */ | |
| import collection.mutable._ | |
| case class Item( price:Double, count:Int, name:String) { | |
| def prettyPrint:String = s"$name\t\t$price x $count" | |
| } | |
| val order = Buffer[Item]() | |
| def add( n:String, p:Double ) : Unit = order+=Item(p,1,n) | |
| def add( c:Int ):(String,Double)=>Unit = (n:String, p:Double)=>order+=Item(p,c,n) | |
| def rm(c:Int):Unit = order.remove(c) | |
| def setCount( idx:Int, newCount: Int ):Unit = { | |
| val old = order.remove(idx); | |
| order.insert(idx, old.copy(count=newCount) ) | |
| } | |
| def setPrice(idx: Int, newPrice: Double): Unit = { | |
| val old = order.remove(idx) | |
| order.insert(idx, old.copy(price = newPrice)) | |
| } | |
| def dump:Unit = order.foreach( i => println(s"meal add i(\"${i.name}\", ${i.price}, ${i.count})")) | |
| def i(n:String, p:Double):Item = Item(p,1,n) | |
| def i(n:String, p:Double, c:Int):Item = Item(p,c,n) | |
| def clear:Unit = order.clear() | |
| object meal { | |
| infix def add(i:Item):Unit = order+=i | |
| def add(s:String, p:Double):Unit = order+=Item(p,1,s) | |
| } | |
| def ll:Unit = { | |
| val longestName = order.map(_.name.length).max | |
| order.zipWithIndex.foreach( itm => println( String.format(s"%02d %-${longestName}s % 6.02f x %d", itm._2, itm._1.name, itm._1.price, itm._1.count ) )) | |
| val sum = order.map( i => i.count*i.price ).sum | |
| println("-------------------") | |
| println(String.format("Meal: % 7.02f", sum) ) | |
| println(String.format("Tax: % 7.02f", sum*0.07) ) | |
| println(String.format("Tip (12%%): % 7.02f", sum*0.12) ) | |
| println(String.format("Total: % 7.02f", sum*1.19) ) | |
| println("-------------------") | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment