Skip to content

Instantly share code, notes, and snippets.

@graciano
Created July 22, 2019 17:21
Show Gist options
  • Save graciano/9b29b166e72a74f28e29a5559c65d24f to your computer and use it in GitHub Desktop.
Save graciano/9b29b166e72a74f28e29a5559c65d24f to your computer and use it in GitHub Desktop.
human readable time code wars
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