Last active
August 29, 2015 13:57
-
-
Save gberger/9656897 to your computer and use it in GitHub Desktop.
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
fromNow = (d) -> | |
unless d instanceof Date | |
d = new Date(d) | |
difference = d - new Date() | |
# string, limit, divider | |
limits = [ | |
["momentos", 1000, 1] | |
["%d segundos", 1000*60, 1000] | |
["um minuto", 1000*60*2, 1000*60] | |
["%d minutos", 1000*60*60, 1000*60] | |
["uma hora", 1000*60*60*2, 1000*60*60] | |
["%d horas", 1000*60*60*24, 1000*60*60] | |
["um dia", 1000*60*60*24*2, 1000*60*60*24] | |
["%d dias", 1000*60*60*24*30, 1000*60*60*24] | |
["um mês", 1000*60*60*24*30*2, 1000*60*60*24*30] | |
["%d meses", 1000*60*60*24*30*12, 1000*60*60*24*30] | |
["um ano", 1000*60*60*24*30*12*2, 1000*60*60*24*30*12] | |
["%d anos", Infinity, 1000*60*60*24*30*12] | |
] | |
# past or future | |
# tiny tolerance to permit for `fromNow(new Date())` to be in the past | |
str = if difference <= 5 then 'há %s' else 'em %s' | |
difference = Math.abs(difference) | |
limit = do (difference) -> | |
for limit in limits | |
if difference < limit[1] | |
return limit | |
return str.replace('%s', limit[0].replace('%d', (difference/limit[2]).toFixed(0))) |
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
fromNow = function(d) { | |
var difference, limit, limits, str; | |
if (!(d instanceof Date)) { | |
d = new Date(d); | |
} | |
difference = d - new Date(); | |
// string, limit, divider | |
limits = [ | |
["momentos", 1000, 1], | |
["%d segundos", 1000*60, 1000], | |
["um minuto", 1000*60*2, 1000*60], | |
["%d minutos", 1000*60*60, 1000*60], | |
["uma hora", 1000*60*60*2, 1000*60*60], | |
["%d horas", 1000*60*60*24, 1000*60*60], | |
["um dia", 1000*60*60*24*2, 1000*60*60*24], | |
["%d dias", 1000*60*60*24*30, 1000*60*60*24], | |
["um mês", 1000*60*60*24*30*2, 1000*60*60*24*30], | |
["%d meses", 1000*60*60*24*30*12, 1000*60*60*24*30], | |
["um ano", 1000*60*60*24*30*12*2, 1000*60*60*24*30*12], | |
["%d anos", Infinity, 1000*60*60*24*30*12] | |
]; | |
str = difference <= 5 ? 'há %s' : 'em %s'; | |
difference = Math.abs(difference); | |
limit = (function(difference) { | |
var _i, _len; | |
for (_i = 0, _len = limits.length; _i < _len; _i++) { | |
limit = limits[_i]; | |
if (difference < limit[1]) { | |
return limit; | |
} | |
} | |
})(difference); | |
return str.replace('%s', limit[0].replace('%d', (difference / limit[2]).toFixed(0))); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Beautiful usage of
do
:)