Skip to content

Instantly share code, notes, and snippets.

@will-clarke
Created October 5, 2016 20:36
Show Gist options
  • Save will-clarke/5eaa5b8ef96d8b1be749c690dee332f3 to your computer and use it in GitHub Desktop.
Save will-clarke/5eaa5b8ef96d8b1be749c690dee332f3 to your computer and use it in GitHub Desktop.
class Checkout
attr_reader :basket, :pricing_rules
def initialize(pricing_rules)
@basket = []
@pricing_rules = pricing_rules
end
# [
# bogof: [ product_code ],
# bulk_discount: [ product_code, new_unit_price, min_number ]
# ]
def scan(item_code)
basket << item(item_code)
end
def total
discount = 0
basket.group_by{|i| i[:code]}.each do |code, grouping| #=> [[3 rasberries], [2 soe]]
discount -= discounts(code, grouping)
end
basket.inject(discount) { |sum, i| sum += i[:price]; sum }
end
def discounts(code, grouping)
discount = 0
if pricing_rules[:bogof].include? code
return (grouping.count / 2) * grouping.first[:price]
end
return discount
end
def item(item_code)
{
'FR1' => { code: 'FR1', name: 'Fruit Tea', price: 311 },
'SR1' => { code: 'SR1', name: 'Strawberries', price: 500 },
'CF1' => { code: 'CF1', name: 'Coffee', price: 1123 },
}[item_code]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment