Skip to content

Instantly share code, notes, and snippets.

@thiagomoretto
Last active August 29, 2015 13:56
Show Gist options
  • Save thiagomoretto/8993723 to your computer and use it in GitHub Desktop.
Save thiagomoretto/8993723 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'json'
@products = {
1 => { :name => 'A' },
2 => { :name => 'B' },
3 => { :name => 'C' },
4 => { :name => 'D' },
5 => { :name => 'E' },
6 => { :name => 'F' }
}
@prices = {
1 => 100,
2 => 200,
3 => 300,
4 => 400,
5 => 500,
6 => 600
}
@discounts = {
"partner1" => 10,
"partner2" => 20,
"partner3" => 30
}
def get_price_of(id, partner)
@prices[id] - (@prices[id] * (@discounts[partner] / 100.0))
end
def get_partners
%w{ partner1 partner2 partner3 }
end
def execute(source)
source.map{ |k, v| k }.
product(get_partners()).
map{ |k, v| { k => { :prices => { v => get_price_of(k, v) } } } }.
group_by{ |v| v.keys[0] }.
map{ |k, v| { k => v.map{ |s| s[k][:prices] }.reduce(:merge) } }.
reduce({}) { |h,o| h[o.keys[0]] = o.values[0]; h }.
merge(source) { |key,f,s| f.merge(s) }
end
# Run
# ruby test1.rb | python -mjson.tool
puts execute(@products).to_json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment