JSFiddle - React, Tailwind, and code Playground
HTML
<p>
Check it out, dude. You use an object, `DURATION_IN_SECONDS`, to define, well, the duration of each epoch in seconds. No magic numbers, sprinkled throughout functions, nobody's guessing what's happending. You also specify the epochs in the order you want them checked, and you have cross-browser compatibility since you're not relying on `Object.keys`.
</p>
<p>
Second, you have ONE FUNCTION, `getDuration`, that does your interval checking. That means, for example, if you want to change the way you compute the interval from `Math.floor` to `Math.round`, you change it ONE TIME.
</p>
<p>
The function `timeSince` is now MUCH more readable, easier to debug, and you don't have to scroll to realize it will also pluralize the epoch (e.g., "years") if necessary.
</p>
<p>
"Clean Code", by Robert C. Martin. I recommend it.
</p>
JavaScript
var DURATION_IN_SECONDS = {
epochs: ['year', 'month', 'day', 'hour', 'minute'],
year: 31536000,
month: 2592000,
day: 86400,
hour: 3600,
minute: 60
};
function getDuration(seconds) {
var epoch, interval;
for (var i = 0; i < DURATION_IN_SECONDS.epochs.length; i++) {
epoch = DURATION_IN_SECONDS.epochs[i];
interval = Math.floor(seconds / DURATION_IN_SECONDS[epoch]);
if (interval >= 1) {
return { interval: interval, epoch: epoch };
}
}
};
function timeSince(date) {
var seconds = Math.floor((new Date() - new Date(date)) / 1000);
var duration = getDuration(seconds);
var suffix = (duration.interval > 1 || duration.interval === 0) ? 's' : '';
return duration.interval + ' ' + duration.epoch + suffix;
};
alert(timeSince('2015-01-01'));