【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;
};
上一篇:Node.js核心模块-stream流


下一篇:信号报告——mooc《零基础学Java语言》-(浙大翁凯)第二周编程题(2)