Last active
February 18, 2019 17:55
-
-
Save 0legovich/c51395dc81d0334f5ce768520aae447d to your computer and use it in GitHub Desktop.
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
class Checkout | |
attr_reader :items, :pricing_rules | |
def initialize(pricing_rules) | |
@pricing_rules = pricing_rules | |
@items = [] | |
end | |
def add(item) | |
items.push item | |
end | |
def total | |
process_rules | |
items.sum { |item| item.cost_with_discount } | |
end | |
private | |
def process_rules | |
pricing_rules.each do |type, rule| | |
items_by_rule = items.select { |item| item.type.to_sym == type } | |
process_discount(rule[:action]) if items_by_rule.count >= rule[:min_count] | |
end | |
end | |
def process_discount(action) | |
case action | |
when :each_PC_minus_20percent | |
items.select { |item| item.type == 'PC' }.each { |item| item.cost_with_discount = item.cost - item.cost * 20 / 100 } | |
when :plus_1_CC | |
cc_items = items.select { |item| item.type == 'CC' } | |
if cc_items.count > 1 | |
free_cc_items = cc_items.count / 2 | |
cc_items.first(free_cc_items).each { |item| item.cost_with_discount = 0 } | |
end | |
end | |
end | |
end | |
class Item | |
attr_reader :cost, :type | |
attr_accessor :cost_with_discount | |
def initialize(data) | |
@type = data[:type] | |
@name = data[:name] | |
@cost = data[:cost] | |
@cost_with_discount = data[:cost] | |
end | |
end | |
pricing_rules = { PC: { min_count: 3, action: :each_PC_minus_20percent }, CC: { min_count: 1, action: :plus_1_CC } } | |
co = Checkout.new(pricing_rules) | |
items_data = [ | |
{ type: 'CC', name: 'Кока-Кола', cost: 1.50 }, | |
{ type: 'CC', name: 'Кока-Кола', cost: 1.50 }, | |
{ type: 'PC', name: 'Пепси Кола', cost: 2.00 }, | |
{ type: 'PC', name: 'Пепси Кола', cost: 2.00 }, | |
{ type: 'PC', name: 'Пепси Кола', cost: 2.00 }, | |
{ type: 'WA', name: 'Вода', cost: 0.85 } | |
] | |
items_data.each do |item_data| | |
co.add(Item.new(item_data)) | |
end | |
p co.total |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment