Last active
July 29, 2018 08:15
-
-
Save lisovskyvlad/8ccce220f4e24621e9c45dcd4ca642ea to your computer and use it in GitHub Desktop.
Ruby solution for the task mentioned in the article http://grishaev.me/why-clj
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 MiddleRate | |
attr_reader :data | |
def initialize(data) | |
@data = data | |
end | |
def call | |
# age rates got { 18 => [30, 15], 50 => [35] } | |
age_rates = data.each_with_object(memory_hash) do |data_item, acc| | |
acc[data_item[:age]].push(data_item[:rate]) | |
end | |
age_rates.reduce({}) do |acc, (age, rates)| | |
acc.merge(age => rates.reduce(:+).to_f / rates.count) | |
end | |
end | |
private | |
def memory_hash | |
Hash.new { |hash, key| hash[key] = [] } | |
end | |
end |
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
require './middle_rate.rb' | |
RSpec.describe MiddleRate do | |
subject(:middle_rate) { described_class.new(data) } | |
let(:data) do | |
[{ age: 18, rate: 30 }, | |
{ age: 18, rate: 15 }, | |
{ age: 50, rate: 35 }] | |
end | |
let(:expected_output) do | |
{ 18 => 22.5, 50 => 35.0 } | |
end | |
it 'computes the middle rate' do | |
expect(middle_rate.call).to eq expected_output | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment