1
0

Optimize lowest price for package size lookup

This commit is contained in:
Tim Kächele 2021-11-20 20:53:47 +01:00
parent 31b0cbd896
commit c6b32d66c7

View File

@ -7,6 +7,7 @@ module PlanetExpress
def initialize(data: nil) def initialize(data: nil)
@data = data || default_data @data = data || default_data
calculate_provider_size_lookup_table calculate_provider_size_lookup_table
calculate_lowest_price_lookup_table
end end
def find_by_provider_and_package_size(provider, package_size) def find_by_provider_and_package_size(provider, package_size)
@ -14,11 +15,12 @@ module PlanetExpress
end end
def lowest_price_for_package_size(package_size) def lowest_price_for_package_size(package_size)
where(package_size: package_size).map(&:price_in_cents).min lowest_price_lookup_table[package_size]
end end
private private
attr_reader :provider_size_lookup_table
attr_reader :provider_size_lookup_table, :lowest_price_lookup_table
def default_data def default_data
[ [
@ -36,5 +38,17 @@ module PlanetExpress
[option.provider, option.package_size] [option.provider, option.package_size]
end end
end end
def calculate_lowest_price_lookup_table
available_package_sizes = data.map { |option| option.package_size }.uniq
lowest_price_per_option_tuples = available_package_sizes.map do |package_size|
option = data.select { |option| option.package_size == package_size }
.min_by { |option| option.price_in_cents }
[option.package_size, option.price_in_cents]
end
@lowest_price_lookup_table = Hash[lowest_price_per_option_tuples]
end
end end
end end