Add an option on a getDuration function

33 Views Asked by At

I actually search how can I add an option to have days in extra to my code. If someone can help I will be very very granted !

const portionTime = durationInSeconds => {

let hours = durationInSeconds / 3600;
let mins = (durationInSeconds % 3600) / 60;
let secs = (mins * 60) % 60;

hours = Math.trunc(hours);
mins = Math.trunc(mins);

if (!hours && !mins && !secs) {
  return "None";
}

if (hours) {
  if (mins) {
    return secs
      ? `${hours} hr ${mins} min & ${secs} sec`
      : `${hours} hr & ${mins} min`;
  } else {
    return secs ? `${hours} hr & ${secs} sec` : `${hours} hr`;
  }
} else {
  if (mins) {
    return secs ? `${mins} min & ${secs} sec` : `${mins} min`;
  } else {
    return secs ? `${secs} sec` : `None`;
  }
}

};```
1

There are 1 best solutions below

0
Brother58697 On

I used the modulus % for the hours, and calculated the days normally the same way you did originally for the hours.

I also implemented the conditions in a different way to make it a bit shorter.

const portionTime = durationInSeconds => {

  let days = (durationInSeconds / (3600 * 24));
  let hours = (durationInSeconds / 3600) % 24;
  let mins = (durationInSeconds / 60) % 60 ;
  let secs = durationInSeconds % 60;

  days = Math.trunc(days);
  hours = Math.trunc(hours);
  mins = Math.trunc(mins);
  
  const dayText = days? days + ' days ' : ''
  const hoursText = hours? hours + ' hr ' : ''
  const minText = mins? mins + ' min ' : ''
  const secsText = secs? secs + ' sec' : ''
  
  return (dayText + hoursText + minText + secsText || 'None')
  
}
console.log(360702 + ' seconds: ' + portionTime(360702))
console.log(3600 + ' seconds: ' + portionTime(3600))
console.log(75 + ' seconds: ' + portionTime(75))
console.log(0 + ' seconds: ' + portionTime(0))