1. 程式人生 > 其它 >【CodeWars】Human readable duration format時間可讀化

【CodeWars】Human readable duration format時間可讀化

比較簡單的一道題
題目要求是把秒數轉化成字串:

formatDuration(62)    // returns "1 minute and 2 seconds"
formatDuration(3662)  // returns "1 hour, 1 minute and 2 seconds"

答案:

const YEAR = 86400 * 365;
const DAY = 86400;
const HOUR = 3600;
const MIN = 60;
const SEC = 1;
const MAP = {
  0: "year",
  1: "day",
  2: "hour",
  3: "minute",
  4: "second",
};

const formatDuration = (givenTime) => {
  let time = givenTime;
  const resArr = [];
  [YEAR, DAY, HOUR, MIN, SEC].forEach((num, index) => {
    const temp = Math.floor(time / num);
    if (temp > 0) {
      if (temp === 1) {
        resArr.push(`1 ${MAP[index]}`);
      } else {
        resArr.push(`${temp} ${MAP[index]}s`);
      }
      time = time - temp * num;
    }
  });
  if (resArr.length === 0) {
    return "now";
  }
  const res = resArr.reverse().reduce((a, c, index) => {
    switch (index) {
      case 0:
        return c;
      case 1:
        return `${c} and ${a}`;
      case 2:
      case 3:
      case 4:
        return `${c}, ${a}`;
      default:
        break;
    }
  });
  return res;
};