Last active
May 9, 2018 08:45
-
-
Save gerardvcruz/af516331405c417c59df7a4e7c5032e9 to your computer and use it in GitHub Desktop.
Fruits!
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
require 'rspec' | |
# The goal is to make the tests pass | |
# Get the cheapest price for each seller. | |
# Seller x the priority seller. | |
# returs a hash containing fruits, | |
# sub keys under fruits are prices | |
# and fruit "keys" | |
def fruits_prices(sellers) | |
# sellers is a hash of sellers who have multiple fruits | |
cheapest_prices = {} | |
sellers.each do |fruits| | |
fruits.each do |fruit, info| | |
if cheapest_prices[:"#{fruit}"].nil? | |
cheapest_prices[:"#{fruit}"] = info | |
# you can set the operator to less than (<) | |
# if you want to prioritize sellers by | |
# order of appearance in params | |
elsif info[:price] <= cheapest_prices[:"#{fruit}"][:price] | |
cheapest_prices[:"#{fruit}"] = info | |
end | |
end | |
end | |
cheapest_prices | |
end | |
RSpec.describe "fruits_prices" do | |
let(:seller_x_result) { { | |
apple: { price: 40, key: 'x-1', additional: 'no children' }, | |
orange: { price: 40, key: 'x-2' }, | |
mango: { price: 100, key: 'x-3' }, | |
grape: { price: 200, key: 'x-4' } | |
} } | |
let(:seller_y_result) { { | |
apple: { price: 50, key: 'y-1'}, | |
grape: { price: 170, key: 'y-4'} | |
} } | |
let(:seller_a_result) { { | |
orange: { price: 30, key: 'a-2' }, | |
mango: { price: 100, key: 'a-3' }, | |
grape: { price: 140, key: 'a-4' } | |
} } | |
let(:seller_b_result) { { | |
grape: { price: 120, key: 'b-4' }, | |
lemon: { price: 80, key: 'b-5' } | |
} } | |
it "works" do | |
result = fruits_prices([seller_x_result, seller_y_result, seller_a_result, seller_b_result]) | |
expect(result[:apple]).to eq(seller_x_result[:apple]) | |
expect(result[:orange]).to eq(seller_a_result[:orange]) | |
# if seller_x is priority then the expected result should be seller_x[:mango] | |
expect(result[:mango]).to eq(seller_a_result[:mango]) | |
expect(result[:grape]).to eq(seller_b_result[:grape]) | |
expect(result[:lemon]).to eq(seller_b_result[:lemon]) | |
result = fruits_prices([seller_x_result, seller_y_result]) | |
expect(result[:apple]).to eq(seller_x_result[:apple]) | |
expect(result[:orange]).to eq(seller_x_result[:orange]) | |
expect(result[:mango]).to eq(seller_x_result[:mango]) | |
expect(result[:grape]).to eq(seller_y_result[:grape]) | |
result = fruits_prices([seller_x_result]) | |
expect(result).to eq(seller_x_result) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment