Created
August 3, 2011 22:16
-
-
Save gotjosh/1123943 to your computer and use it in GitHub Desktop.
Answer to Headshift's Rails Test
This file contains hidden or 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
# encoding: UTF-8 | |
class Checkout | |
@@current_items = {} | |
@@stock_items = {} | |
def initialize(pricing_rules) | |
# Sets the current_items hash to store the amount/type of items | |
set_items(pricing_rules) | |
end | |
def scan(item) | |
# Iterate over each key to check if it's available and add an item to it | |
@@current_items.each do |key, value| | |
if key == item.upcase.to_sym | |
@@current_items[key] += 1 | |
end | |
end | |
end | |
def total | |
# Apply the offers rules before calculating the total | |
apply_offer_rules | |
total = 0 | |
@@current_items.each do |key,value| | |
total += (value * @@stock_items[key]).round(2) | |
end | |
humanize_total(total) | |
end | |
private | |
# Prepare both the @@current_items and @@stock_items hashes with the | |
# pricing_rules | |
def set_items(pricing) | |
pricing.each do |key, value| | |
@@current_items[key.to_sym] = 0 | |
@@stock_items[key.to_sym] = value | |
end | |
end | |
def humanize_total(amount) | |
puts "€" + amount.to_s | |
end | |
def apply_offer_rules | |
# If you buy more than 2 strawberries price drops to 4.50 | |
if @@current_items[:SR1] > 2 | |
@@stock_items[:SR1]= 4.50 | |
end | |
# If you have an even amount of Fruit tea cut down the price by hal | |
# Otherwise drop the price and add one item because you get one free :-) | |
if @@current_items[:FR1].even? | |
@@stock_items[:FR1] = @@stock_items[:FR1] / 2 | |
else | |
@@stock_items[:FR1] = @@stock_items[:FR1] / 2 | |
@@current_items[:FR1] += 1 | |
end | |
end | |
end | |
rules = {:FR1 => 3.11, :SR1 => 5.00, :CF1 => 11.23 } | |
co1 = Checkout.new(rules) | |
# Basket: SR1,SR1,FR1,SR1 | |
co1.scan('sr1') | |
co1.scan('sr1') | |
co1.scan('fr1') | |
co1.scan('sr1') | |
co1.total | |
co1 = Checkout.new(rules) | |
# Basket: FR1,FR1 | |
co1.scan('fr1') | |
co1.scan('fr1') | |
co1.total | |
co1 = Checkout.new(rules) | |
# Basket: FR1,SR1,FR1,FR1,CF1 | |
co1.scan('fr1') | |
co1.scan('sr1') | |
co1.scan('fr1') | |
co1.scan('fr1') | |
co1.scan('cf1') | |
co1.total |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment