-
-
Save chrismdp/a89d528d7055c2b975ccaa532fbc41db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def assert_equal(expected, actual) | |
print expected == actual ? "." : "Expected #{expected.inspect} but got #{actual.inspect}\n" | |
end | |
Discount = Struct.new(:amount, :value) do | |
def apply(basket, item) | |
(basket.count(item)/amount) * value | |
end | |
end | |
# same as... | |
class Discount | |
def initialize(amount, value) | |
@amount = amount | |
@value = value | |
end | |
def apply(basket, item) | |
(basket.count(item)/@amount) * @value | |
end | |
end | |
class Checkout | |
PRODUCTS = { | |
"A" => { | |
price: 50, | |
discount: Discount.new(3, -20) | |
}, | |
"B" => { | |
price: 30, | |
discount: Discount.new(2, -15) | |
} | |
} | |
def initialize | |
@basket = [] | |
end | |
def scan(item) | |
@basket.push(item) | |
end | |
def total | |
PRODUCTS.keys.map do |item| | |
@basket.count(item) * PRODUCTS[item][:price] + PRODUCTS[item][:discount].apply(@basket, item) | |
end.reduce(:+) | |
end | |
end | |
checkout = Checkout.new | |
assert_equal(0, checkout.total) | |
checkout.scan("A") | |
assert_equal(50, checkout.total) | |
checkout.scan("B") | |
assert_equal(80, 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") | |
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