Skip to content

Instantly share code, notes, and snippets.

@agemooij
Last active August 29, 2015 14:05
Show Gist options
  • Save agemooij/9601660e169ffa57bfe7 to your computer and use it in GitHub Desktop.
Save agemooij/9601660e169ffa57bfe7 to your computer and use it in GitHub Desktop.
def addItem(newItem: BasketItem): BasketState = {
copy(
items.foldRight((false, List.empty[BasketItem])) {
case (item, (_, out)) if (item.matchesProductAndSizeOf(newItem)) ⇒ (true, item.incrementNumberBy(newItem.numberOfProducts) :: out)
case (item, (didSomethingMatch, out)) ⇒ (didSomethingMatch, item :: out)
} match {
case (false, _) ⇒ newItem :: items
case (true, modifiedItems) ⇒ modifiedItems
}
)
}
case class BasketState(items: List[BasketItem] = Nil) {
def addItem(newItem: BasketItem): BasketState = {
// if (items.exists(item ⇒ item.productNumber == newItem.productNumber && item.sizeCode == newItem.sizeCode)) {
// copy(
// items.map { item ⇒
// if (item.productNumber == newItem.productNumber && item.sizeCode == newItem.sizeCode)
// item.copy(numberOfProducts = item.numberOfProducts + 1)
// else item
// }
// )
// } else {
// copy(newItem :: items)
// }
// copy(
// items.foldRight((false, List.empty[BasketItem])) { (item, out) ⇒
// if (item.productNumber == newItem.productNumber && item.sizeCode == newItem.sizeCode)
// (true, item.copy(numberOfProducts = item.numberOfProducts + 1) :: out._2)
// else (false, item :: out._2)
// } match {
// case (false, _) ⇒ newItem :: items
// case (true, modifiedItems) ⇒ modifiedItems
// }
// )
copy(
items.foldRight((false, List.empty[BasketItem])) {
case (item, (_, out)) if (item.productNumber == newItem.productNumber && item.sizeCode == newItem.sizeCode) ⇒ (true, item.copy(numberOfProducts = item.numberOfProducts + newItem.numberOfProducts) :: out)
case (item, (bool, out)) ⇒ (bool, item :: out)
} match {
case (false, _) ⇒ newItem :: items
case (true, modifiedItems) ⇒ modifiedItems
}
)
// copy(
// items.foldRight((false, List.empty[BasketItem])) {
// case (BasketItem(newItem.productNumber, newItem.sizeCode, numberOfProducts, product), (_, out)) ⇒ (true, BasketItem(newItem.productNumber, newItem.sizeCode, numberOfProducts + newItem.numberOfProducts, product) :: out)
// case (item, (bool, out)) ⇒ (bool, item :: out)
// } match {
// case (false, _) ⇒ newItem :: items
// case (true, modifiedItems) ⇒ modifiedItems
// }
// )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment