Skip to content

Instantly share code, notes, and snippets.

@monkeygroover
Created December 16, 2015 21:26
Show Gist options
  • Select an option

  • Save monkeygroover/2b2708edbce6f0880365 to your computer and use it in GitHub Desktop.

Select an option

Save monkeygroover/2b2708edbce6f0880365 to your computer and use it in GitHub Desktop.
case class PermutingCheckout(skuRules: Map[String, SKUPricer]) extends TotalCalculator {
// as above but runs the rules in all permuted orders to find the best order to minimise the price
val calculateTotal = (items: List[String]) =>
items.foldMap(x => Map(x -> 1)) // create a map of SKU -> count of 'scanned' items
.map { case (sku, skuCount) =>
// get the rules for the SKU (if they exist) and map them to get the results for each SKU group
skuRules.get(sku).map(rule => (rule.getPrice(skuCount)).success)
.getOrElse(s"'$sku' rule not found".failureNel)
}.reduce(_ |+| _) // sum the results for each SKU to get the final total
}
// we now have a list of ValidationNel[String, Int] for each permutation
// so sequence to transform List[ValidationNel[String, Int]] to ValidationNel[String, List[Int]]
// and pick the minimum price by mapping the right hand side
totalsList.sequenceU.:->(_.min)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment