Last active
May 16, 2016 06:42
-
-
Save keithrbennett/fd876aac938f1e5d6222896dbd30e8f2 to your computer and use it in GitHub Desktop.
Filling in missing dates
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
#!/usr/bin/env ruby | |
require 'date' | |
def to_date(string) | |
Date.strptime(string, '%Y-%m-%d') | |
end | |
# Transform the input to a hash whose keys are date objects | |
# and whose values are the original input records | |
def transform_input_to_hash(input_records) | |
input_records.each_with_object({}) do |record, hsh| | |
key = to_date(record[:date]) | |
hsh[key] = record | |
end | |
end | |
def fill_in_missing_dates(input_records) | |
input_record_hash = transform_input_to_hash(input_records) | |
start_date = input_record_hash.keys.first | |
output_dates = ((start_date - 6)..start_date).to_a.reverse | |
output_dates.each_with_object([]) do |date, array| | |
array << if input_record_hash.keys.include?(date) | |
input_record_hash[date] | |
else | |
{ date: date, amount: 0 } | |
end | |
end | |
end | |
INPUT_RECORDS = [ | |
{ | |
date: "2016-05-14", | |
amount: 6000 | |
}, | |
{ | |
date: "2016-05-12", | |
amount: 12000 | |
} | |
] | |
output_array = fill_in_missing_dates(INPUT_RECORDS) | |
puts output_array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment