Skip to content

Instantly share code, notes, and snippets.

@KattyaCuevas
Created May 31, 2021 20:18
Show Gist options
  • Save KattyaCuevas/38dcc9bfc05f5e819445af27e380b7e1 to your computer and use it in GitHub Desktop.
Save KattyaCuevas/38dcc9bfc05f5e819445af27e380b7e1 to your computer and use it in GitHub Desktop.
Product = Struct.new(:name, :price)
Offer = Struct.new(:product_name, :min_quantity, :offer_type, :discount) do
def calculate(quantity)
return quantity if min_quantity > quantity
case offer_type
when '2x1' then quantity / 2 + quantity % 2
when 'discount' then (1 - discount.to_f) * quantity
else quantity
end
end
end
class Store
attr_accessor :products, :offers
def initialize
@products = []
@offers = []
end
def find_product(product_name)
@products.detect { |product| product.name == product_name }
end
def find_offer(product_name)
@offers.detect { |offer| offer.product_name == product_name }
end
end
class Checkout
attr_reader :products, :store
def initialize(store)
@products = {}
@store = store
end
def add_product(array)
if @products[array[0]]
@products[array[0]] += array[1]
else
@products[array[0]] = array[1]
end
end
def calculate
products.inject(0) do |total, (name, quantity)|
product = store.find_product(name)
offer = store.find_offer(name)
total_quantity = offer ? offer.calculate(quantity) : quantity
total + total_quantity * product.price
end
end
end
store = Store.new
store.products << Product.new('grapes', 5)
store.products << Product.new('apples', 3)
store.products << Product.new('peaches', 7)
store.offers << Offer.new('grapes', 2, '2x1')
store.offers << Offer.new('apples', 2, 'discount', 0.2)
products = [['grapes', 1], ['apples', 0], ['peaches', 1]]
# products = [['grapes', 1], ['apples', 1], ['peaches', 1]]
# products = [['grapes', 2], ['apples', 2], ['peaches', 1]]
# products = [['grapes', 3], ['apples', 5], ['peaches', 2]]
# products = [['peaches', 7], ['grapes', 7], ['apples', 7]]
checkout = Checkout.new(store)
products.map { |product| checkout.add_product(product) }
p checkout.calculate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment