public VendingMachine(IDispenseProduct dispenser) { _dispenser = dispenser; _productStock = _productCatalog.Keys.ToDictionary(k => k, s => 0); _coinStock = new CoinBag(_weightToValueMap); _currentMessage = GetDefaultMessage(); }
private void VerifyCoinBagsAcceptSameTypes(CoinBag otherBag) { if (!_coinQuantities.Keys.OrderBy(x => x).SequenceEqual(otherBag._coinQuantities.Keys.OrderBy(x => x))) { throw new InvalidOperationException("these bags map to different coin types"); } }
public CoinBag Without(CoinBag otherBag) { VerifyCoinBagsAcceptSameTypes(otherBag); var amounts = _coinQuantities.ToDictionary(x => x.Key, x => Math.Max(x.Value - otherBag._coinQuantities[x.Key], 0)); return(new CoinBag(_valueMap, amounts)); }
public CoinBag Merge(CoinBag otherBag) { VerifyCoinBagsAcceptSameTypes(otherBag); var amounts = _coinQuantities.ToDictionary(x => x.Key, x => x.Value + otherBag._coinQuantities[x.Key]); return(new CoinBag(_valueMap, amounts)); }
public void SelectProduct(string productCode) { productCode = SanitizeProductCode(productCode); //Postel's Law ;-) if (!_productCatalog.ContainsKey(productCode)) { return; } if (_productStock[productCode] <= 0) { _currentMessage = "SOLD OUT"; return; } var productPrice = _productCatalog[productCode]; _currentMessage = string.Format("PRICE {0:C}", productPrice); var currentAmount = GetCurrentAmount(); if (currentAmount < productPrice) { return; } var changeDue = currentAmount - productPrice; var coinStockAndInserted = _coinStock .WithCoins(_coinsInserted); if (!coinStockAndInserted.CanMakeChange(changeDue)) { _currentMessage = "EXACT CHANGE ONLY"; return; } var coinsToReturn = coinStockAndInserted .MakeChange(changeDue); _coinStock = coinStockAndInserted.Without(coinsToReturn); _coinsInserted.Clear(); _currentMessage = "THANK YOU"; _dispenser.DispenseProduct(productCode); _coinReturn.AddRange(coinsToReturn.ToCoins()); }
public void StockCoins(IDictionary <double, int> coinQuantities) { _coinStock = new CoinBag(_weightToValueMap, coinQuantities); _currentMessage = GetDefaultMessage(); }