Skip to content

Instantly share code, notes, and snippets.

@jayphelps
Created August 21, 2019 02:30
Show Gist options
  • Save jayphelps/acf30dbb5a130da01fa861db32bc0367 to your computer and use it in GitHub Desktop.
Save jayphelps/acf30dbb5a130da01fa861db32bc0367 to your computer and use it in GitHub Desktop.
// noprotect
console.clear();
const second = 1;
const minute = second * 60;
const hour = minute * 60;
const day = hour * 24;
const year = day * 365;
const unitValues = [{
unit: 'year',
value: year
}, {
unit: 'day',
value: day
}, {
unit: 'hour',
value: hour
}, {
unit: 'minute',
value: minute
}, {
unit: 'second',
value: second
}];
function formatDuration(inputSecs) {
if (typeof inputSecs !== 'number' || inputSecs < 0 || isNaN(inputSecs)) {
throw new TypeError('formatDuration() may only be called with a non-negative number');
}
if (inputSecs === 0) {
return 'now';
}
const parts = [];
let secsRemaining = inputSecs;
for (const { unit, value } of unitValues) {
const count = Math.floor(secsRemaining / value);
if (count > 0) {
secsRemaining -= count * value;
const label = count > 1 ? unit + 's' : unit;
parts.push(`${count} ${label}`);
}
}
if (parts.length === 1) {
return parts[0];
}
const last = parts.pop();
return `${parts.join(', ')} and ${last}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment