Created
August 21, 2019 02:30
-
-
Save jayphelps/acf30dbb5a130da01fa861db32bc0367 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
// 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