Created
February 6, 2012 22:46
-
-
Save yalestar/1755636 to your computer and use it in GitHub Desktop.
Find the longest streak of consecutive dates
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
dates = thing.order("created_at DESC").map(&:created_at) | |
longest = 1 | |
streaks = [] | |
return 0 if dates.nil? || dates.empty? | |
dates.each_with_index do |d, idx| | |
unless (idx == dates.size - 1) | |
d1 = dates[idx] | |
d2 = dates[idx + 1] | |
td = (d2-d1) / 1.day | |
if (0..1).include?(td) # start counting the streak | |
longest += 1 | |
else | |
# add that streak to the list and reset it | |
streaks << longest | |
longest = 0 | |
end | |
end | |
end | |
streaks.uniq.max || 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment