ms、s、min、h单位换算代码可以再优化吗?

2023-03-30 0 1,519
export const timeConvert = function (timeValue) {
  if (isNaN(timeValue)) {
    return '';
  }
  const baseUnitLabel = ['ms', 's', 'min', 'h'];
  const basicValue = [1,1000,1000*60,1000*60*60]
  const exp1 = Math.floor(timeValue / 1000);
  let exp2;
  if (exp1 < 1) {
    exp2 = 0
  } else if (exp1 < 60) {
    exp2 =  1
  } else if(exp1 < 60 * 60)  {
    exp2 = 2
  } else {
    exp2 = 3
  }
  let resValue = timeValue/basicValue[exp2]
  if (resValue.toString().length > resValue.toFixed(2).toString().length) {
    resValue = resValue.toFixed(2);
  }
  return `${resValue} ${baseUnitLabel[exp2]}`;
};

之后优化修改

export const timeConvert = function (timeValue) {
  if (isNaN(timeValue) || typeof timeValue != 'number') {
    return '';
  }
  const baseUnitLabel = ['ms', 's', 'min', 'h'];
  const baseUnitValue = [1,1000,1000*60,1000*60*60]
  const formatValue = Math.floor(timeValue / 1000);
  let resIndex;
  if (formatValue < 1) {
    resIndex = 0
  } else {
    const value = Math.floor(Math.log(formatValue) / Math.log(60)) + 1;
    resIndex = value > 3? 3: value
  }
  let resValue = timeValue / baseUnitValue[resIndex]
  if (resValue.toString().length > resValue.toFixed(2).length) {
    resValue = resValue.toFixed(2);
  }
  return `${resValue} ${baseUnitLabel[resIndex]}`;
};
export const timeConvert = function (timeValue) {
    if (!(typeof timeValue === "number" && timeValue >= 0)) {
        return "";
    }

    const baseUnitLabel = ["ms", "s", "min", "h"];
    const basicValue = [1, 1000, 1000 * 60, 1000 * 60 * 60];

    let index = Math.max(basicValue.findLastIndex(basic => timeValue > basic), 0)
    
    return `${Number((timeValue / basicValue[index]).toFixed(2))} ${baseUnitLabel[index]}`;
};

简单的优化了一下

 export const timeConvert =  function (timeValue) {
    if (isNaN(timeValue) || typeof timeValue != 'number') {
      return '';
    }
    const baseUnitLabel = ['ms', 's', 'min', 'h'];
    const basicValue = [1, 1000, 1000 * 60, 1000 * 60 * 60]
    const exp1 = Math.floor(timeValue / 1000);
    let exp2 = 3;
    if (exp1 < 1) {
      exp2 = 0
    } else if (exp1 < 60) {
      exp2 = 1
    } else if (exp1 < 60 * 60) {
      exp2 = 2
    }
    let resValue = timeValue / basicValue[exp2]
    if (resValue.toString().length > resValue.toFixed(2).length) {
      resValue = Math.round((resValue + Number.EPSILON) * 100) / 100;
    }
    return `${resValue} ${baseUnitLabel[exp2]}`;
  };
ms、s、min、h单位换算代码可以再优化吗?
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

1. JK下载官网所有资源来源于开发团队,加入会员即可下载使用!如有问题请联系右下角在线客服!
2. JK下载官方保障所有软件都通过人工亲测,为每位会员用户提供安全可靠的应用软件、游戏资源下载及程序开发服务。
3. JK开发团队针对会员诉求,历经多年拥有现今开发成果, 每款应用程序上线前都经过人工测试无误后提供安装使用,只为会员提供安全原创的应用。
4. PC/移动端应用下载后如遇安装使用问题请联系右下角在线客服或提交工单,一对一指导解决疑难。

JK软件下载官网 技术分享 ms、s、min、h单位换算代码可以再优化吗? https://www.jkxiazai.com/1118.html

JK软件应用商店是经过官方安全认证,保障正版软件平台

相关资源

官方客服团队

为您解决烦忧 - 24小时在线 专业服务