-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCheckout.cs
67 lines (52 loc) · 1.73 KB
/
Checkout.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
namespace Checkout
{
using System;
using System.Collections.Generic;
public class Checkout
{
// IDictionary used to access elements by keys. Will store quantity and total price
private IDictionary<string, IDictionary<int, int>> _price;
private Dictionary<string, int> _currentBasket = new();
public Checkout(
IDictionary<string, IDictionary<int, int>> pricing)
{
_price = pricing;
}
// Key/value pairs, allows them to be enumerated
public Dictionary<string, int> Basket => _currentBasket;
public void Add(string item)
{
// make sure string passed is valid
if (string.IsNullOrWhiteSpace(item))
{
throw new ArgumentNullException("item cannot be blank");
}
// add item to current basket
if (!_currentBasket.ContainsKey(item))
{
_currentBasket[item] = 0;
}
_currentBasket[item]++;
}
private int itemPrice(string item, int quantity)
{
var itemPrices = _price[item];
// found an exact match for this quantity
if (itemPrices.ContainsKey(quantity))
{
return itemPrices[quantity];
}
// get closest exact match
var closestQuantity = itemPrices.Keys.First(x => x < quantity);
// work out how many items left to price from exact match quantity
var diffQuantity = quantity - closestQuantity;
// recursively calculate price for remaining items until there are no more items left to price
var price = itemPrices[closestQuantity] + itemPrice(item, diffQuantity);
return price;
}
public int TotalPrice
{
get{ var totalPrice = _currentBasket.Keys.Sum(item => itemPrice(item, _currentBasket[item])); return totalPrice; }
}
}
}