avkvak
10/17/2019 - 6:09 PM

Convert ms to days, hours, minutes, seconds

/**
 * Convert value of milliseconds into hours, seconds, minutes, days
 * @param {number} ms
 * @returns {{hours: number, seconds: number, minutes: number, days: number}}
 */
const convertMs = ms  => {
  const SECOND_IN_MS = 1000;
  const MINUTE_IN_MS = SECOND_IN_MS * 60;
  const HOUR_IN_MS = MINUTE_IN_MS * 60;
  const DAY_IN_MS = HOUR_IN_MS * 24;
  
  const calculateUnitWithMemoizedRest = (unit, initialValue) => {
    if (!('rest' in calculateUnitWithMemoizedRest)) {  
      calculateUnitWithMemoizedRest.rest = initialValue; 
    }

    const calculatedValue = calculateUnitWithMemoizedRest.rest < unit ? 0 : Math.floor(calculateUnitWithMemoizedRest.rest / unit);
    calculateUnitWithMemoizedRest.rest -= calculatedValue * unit;
    return calculatedValue;
  };
  
  return {
    days: calculateUnitWithMemoizedRest(DAY_IN_MS, ms),
    hours: calculateUnitWithMemoizedRest(HOUR_IN_MS),
    minutes: calculateUnitWithMemoizedRest(MINUTE_IN_MS),
    seconds: calculateUnitWithMemoizedRest(SECOND_IN_MS),
  };
}