DEV Community

Discussion on: Daily Challenge #21 - Human Readable Time

Collapse
 
alvaromontoro profile image
Alvaro Montoro

JavaScript

const format_duration = number => {
  if (parseInt(number) && number > 0) {
    // breakpoints: 60 seconds in a minute, 3600 seconds in an hour, etc.
    const bp = [60, 3600, 86400, 31536000, Number.MAX_VALUE];
    const units = ["second", 'minute', 'hour', 'day', 'year'];
    let solution = [];
    for (let x = 0; x < bp.length; x++) {
      if (number % bp[x] !== 0) {
        const value = Math.floor((number % bp[x]) / (bp[x-1] || 1));
        solution.push(`${value} ${units[x]}${value > 1 ? 's' : ''}`);
        number -= number % bp[x];
      }
    }

    // edge case: the value was too large and the modulus was considered 0
    if (number > 0) solution.push(`${number} years`)

    // add the "and" for the last element (because Oxford comma and cheating)
    solution[0] = "and " + solution[0];

    return solution.reverse().join(', ');
  }
  return "Invalid number";
}

With a little bit of cheating: instead of replacing the last comma with an "and", I just add the "and" to the last element and claim that everyone should be using Oxford comma to avoid misunderstandings.

Live demo on CodePen.

Collapse
 
alvaromontoro profile image
Alvaro Montoro

This feels overcomplicated. It probably can be done easier with a map or a reduce. I'll check later with more time.

Collapse
 
nishu1343 profile image
nishu1343

Hello Alvaro. Did u get a chance to work on this?🤓

Thread Thread
 
alvaromontoro profile image
Alvaro Montoro

LOL. I didn't 😓😬

Thread Thread
 
nishu1343 profile image
nishu1343

Thats fine Alvaro. Are u on discord??

Thread Thread
 
alvaromontoro profile image
Alvaro Montoro

Not really. I have only used once or twice.

Thread Thread
 
nishu1343 profile image
nishu1343

Cool.i like the way you explain things man. Just want to be in touch with you to ask some basic doubta as im a beginner. Is there any other way i can be in touch. Do u have wssap? I wont bother u much.dont be scared😅

Thread Thread
 
alvaromontoro profile image
Alvaro Montoro

I'm not going to lie: I've had bad experiences with this in the past. If you have questions and you post them here or in StackOverflow, I'll be happy to look at them and answer if I know the answer.