Created
August 4, 2017 12:25
-
-
Save derekmorr/eff2403d28c65aac1fd6c9a4bcc996c5 to your computer and use it in GitHub Desktop.
shopping cart kata
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
case class MultiPrice(qty: Int, price: Int) | |
case class PriceData( | |
itemPrices: Map[Char, Int], | |
multiPrices: Map[Char, MultiPrice] | |
) | |
object ShoppingCart { | |
def checkout(basket: String, priceData: PriceData): Int = { | |
val itemCounts = basket.groupBy(identity).mapValues(_.length) | |
itemCounts.foldLeft(0) { case (acc, (sku, qty)) => | |
acc + totalPerItem(sku, qty, priceData) | |
} | |
} | |
def totalPerItem(sku: Char, count: Int, priceData: PriceData): Int = { | |
val itemPrice = priceData.itemPrices(sku) // throws on error | |
priceData.multiPrices.get(sku) match { | |
case None => itemPrice * count | |
case Some(mp) => count / mp.qty * mp.price + count % mp.qty * itemPrice | |
} | |
} | |
} | |
object Tests { | |
val pd: PriceData = PriceData( | |
Map('A' -> 50, 'B' -> 30, 'C' -> 20, 'D' -> 15), | |
Map( | |
'A' -> MultiPrice(3, 130), | |
'B' -> MultiPrice(2, 45) | |
) | |
) | |
} | |
class MutableShoppingCart(priceData: PriceData) { | |
private var basket: List[Char] = Nil | |
def scan(sku: Char): Unit = basket = sku +: basket | |
def checkout: Int = ShoppingCart.checkout(basket.mkString, priceData) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment