-
-
Save pjb3/b094867867d9d1d2d5ee to your computer and use it in GitHub Desktop.
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 'time' | |
# Monkeypatching FTW! ;) | |
module Enumerable | |
def sum | |
inject(0){|acc,e| acc + e} | |
end | |
def avg | |
size > 0 ? sum / size : 0 | |
end | |
end | |
class Time | |
ONE_DAY = 60 * 60 * 24 | |
# Returns a 3 element array containing | |
# - the time (self) minus one day | |
# - the time (self) | |
# - the time (self) plus one day | |
def plus_or_minus_one_day | |
[self - ONE_DAY, self, self + ONE_DAY] | |
end | |
# Given an Array of Times, this will returns | |
# a time representing the average all the times | |
def self.avg(times) | |
Time.at(times.map{|t| t.to_i}.avg) | |
end | |
# Given an Array of Times, this will return | |
# the time in the Array that is closest to this Time (self) | |
def closest(times) | |
if times.empty? then self else | |
times.min{|a,b| (self - a).abs <=> (self - b).abs } | |
end | |
end | |
end | |
def average_time_of_day(times_of_day) | |
Time.avg(times_of_day.inject([]) do |times, time_of_day| | |
time = Time.parse(time_of_day) | |
avg = times.empty? ? time : Time.avg(times) | |
times << avg.closest(time.plus_or_minus_one_day) | |
end).strftime("%l:%M%p").downcase.strip | |
end | |
if __FILE__ == $0 | |
puts average_time_of_day(["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"]) | |
puts average_time_of_day(["6:41am", "6:51am", "7:01am"]) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment