其他分享
首页 > 其他分享> > 【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;
};

标签:case,index,const,读化,temp,format,readable,return,resArr
来源: https://www.cnblogs.com/hikki-station/p/14974222.html