Created
July 22, 2019 17:21
-
-
Save graciano/9b29b166e72a74f28e29a5559c65d24f to your computer and use it in GitHub Desktop.
human readable time code wars
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
const quotientFunctions = { | |
year: time => Math.floor(time / (365 * 24 * 60 * 60)), | |
day: time => Math.floor((time / (24 * 60 * 60)) % 365), | |
hour: time => Math.floor((time / (60 * 60)) % 24), | |
minute: time => Math.floor((time / 60) % 60), | |
second: time => Math.floor(time % 60), | |
}; | |
const pluralize = ({ | |
str, | |
quotient | |
}) => quotient > 1 ? `${quotient} ${str}s` : `${quotient} ${str}`; | |
const humanReadable = time => Object.entries(quotientFunctions) | |
.map(([str, quotient]) => ({ | |
str, | |
quotient: quotient(time), | |
})) | |
.filter(({ quotient }) => quotient >= 1) // prevent '0 year 0 day...' polluting the final string | |
.map(pluralize).join(' and '); | |
console.log(humanReadable(62)); | |
console.log(humanReadable(90)); | |
console.log(humanReadable(3662)); | |
console.log(humanReadable(84600)); | |
console.log(humanReadable(120000)); | |
console.log(humanReadable((365 * 24 * 60 * 60 * 2) + (80 * 60 * 60) + 124)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment