Files
ruby-checkout/checkout.rb
T
David Underwood 882c18b5e6 Rebuild the Checkout class, no discounts yet
Checkout now stores its items using a quantity and a link back to the
original product instance. It has a reference to the store to make sure
that product IDs added are valid
2026-07-21 10:27:33 -04:00

44 lines
864 B
Ruby

require 'product_in_checkout.rb'
class Checkout
class InvalidItem < StandardError; end
def initialize(shop:)
@shop = shop
@items = []
end
def add(product_id:, quantity: 1)
product = @shop.product_by_id(product_id)
raise InvalidItem unless product
product_in_checkout = new_or_existing_product_in_checkout(product)
product_in_checkout.add_quantity(quantity)
@items.push product_in_checkout
end
def items
@items
end
def item_quantities
@items.map { |item| [item.product_id, item.quantity] }.to_h
end
def clear
@items = []
end
def total
@items.reduce(0.00) { |running_total, item| running_total + item.total }
end
private
def new_or_existing_product_in_checkout(product)
@items.find { |item| item.product_id == product.id } || ProductInCheckout.new(product: product)
end
end