Skip to content

Instantly share code, notes, and snippets.

@chrismdp
Created June 11, 2019 10:39
Show Gist options
  • Save chrismdp/bba955ce15777516f185a92a87dd2e4b to your computer and use it in GitHub Desktop.
Save chrismdp/bba955ce15777516f185a92a87dd2e4b to your computer and use it in GitHub Desktop.
def assert_equal(expected, actual)
print expected == actual ? "." : "Expected #{expected}, but got #{actual}\n"
end
class PriceRule
def initialize(code, price)
@code = code
@price = price
end
def apply(basket)
basket.count(@code) * @price
end
end
Discount = Struct.new(:code, :number, :amount) do
def apply(basket)
(basket.count(code) / number) * -amount
end
end
#class Discount < Struct.new(:code, :number, :amount)
#def apply(basket)
#(basket.count(code) / number) * -amount
#end
#end
class Discount
def initialize(code, number, amount)
@code = code
@number = number
@amount = amount
end
def apply(basket)
(basket.count(@code) / @number) * -@amount
end
end
class Checkout
def initialize
@basket = []
@rules = [PriceRule.new("A", 50),
PriceRule.new("B", 30),
Discount.new("A", 3, 20),
Discount.new("B", 2, 15)]
end
def total
@rules.map { |r| r.apply(@basket) }.reduce(0, :+)
end
def scan(item)
@basket.push(item)
end
end
checkout = Checkout.new
assert_equal(0, checkout.total)
checkout.scan("A")
assert_equal(50, checkout.total)
checkout = Checkout.new
checkout.scan("A")
checkout.scan("A")
checkout.scan("A")
assert_equal(130, checkout.total)
checkout = Checkout.new
checkout.scan("B")
assert_equal(30, checkout.total)
checkout = Checkout.new
checkout.scan("B")
checkout.scan("B")
assert_equal(45, checkout.total)
puts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment