首页 > 编程语言 >JavaScript 实用工具方法库

JavaScript 实用工具方法库

时间:2023-01-10 19:55:31浏览次数:42  
标签:const 实用工具 JavaScript return item moment path now 方法

 utils.js

import moment from 'moment';

export function fixedZero(val) {
  return val * 1 < 10 ? `0${val}` : val;
}

export function getTimeDistance(type) {
  const now = new Date();
  const oneDay = 1000 * 60 * 60 * 24;

  if (type === 'today') {
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);
    return [moment(now), moment(now.getTime() + (oneDay - 1000))];
  }

  if (type === 'week') {
    let day = now.getDay();
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);

    if (day === 0) {
      day = 6;
    } else {
      day -= 1;
    }

    const beginTime = now.getTime() - day * oneDay;

    return [moment(beginTime), moment(beginTime + (7 * oneDay - 1000))];
  }

  if (type === 'month') {
    const year = now.getFullYear();
    const month = now.getMonth();
    const nextDate = moment(now).add(1, 'months');
    const nextYear = nextDate.year();
    const nextMonth = nextDate.month();

    return [
      moment(`${year}-${fixedZero(month + 1)}-01 00:00:00`),
      moment(moment(`${nextYear}-${fixedZero(nextMonth + 1)}-01 00:00:00`).valueOf() - 1000),
    ];
  }

  if (type === 'year') {
    const year = now.getFullYear();

    return [moment(`${year}-01-01 00:00:00`), moment(`${year}-12-31 23:59:59`)];
  }
}

export function getPlainNode(nodeList, parentPath = '') {
  const arr = [];
  nodeList.forEach(node => {
    const item = node;
    item.path = `${parentPath}/${item.path || ''}`.replace(/\/+/g, '/');
    item.exact = true;
    if (item.children && !item.component) {
      arr.push(...getPlainNode(item.children, item.path));
    } else {
      if (item.children && item.component) {
        item.exact = false;
      }
      arr.push(item);
    }
  });
  return arr;
}

export function digitUppercase(n) {
  const fraction = ['角', '分'];
  const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  const unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
  let num = Math.abs(n);
  let s = '';
  fraction.forEach((item, index) => {
    s += (digit[Math.floor(num * 10 * 10 ** index) % 10] + item).replace(/零./, '');
  });
  s = s || '整';
  num = Math.floor(num);
  for (let i = 0; i < unit[0].length && num > 0; i += 1) {
    let p = '';
    for (let j = 0; j < unit[1].length && num > 0; j += 1) {
      p = digit[num % 10] + unit[1][j] + p;
      num = Math.floor(num / 10);
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
  }

  return s
    .replace(/(零.)*零元/, '元')
    .replace(/(零.)+/g, '零')
    .replace(/^整$/, '零元整');
}

function getRelation(str1, str2) {
  if (str1 === str2) {
    console.warn('Two path are equal!'); // eslint-disable-line
  }
  const arr1 = str1.split('/');
  const arr2 = str2.split('/');
  if (arr2.every((item, index) => item === arr1[index])) {
    return 1;
  } else if (arr1.every((item, index) => item === arr2[index])) {
    return 2;
  }
  return 3;
}

function getRenderArr(routes) {
  let renderArr = [];
  renderArr.push(routes[0]);
  for (let i = 1; i < routes.length; i += 1) {
    let isAdd = false;
    // 是否包含
    isAdd = renderArr.every(item => getRelation(item, routes[i]) === 3);
    // 去重
    renderArr = renderArr.filter(item => getRelation(item, routes[i]) !== 1);
    if (isAdd) {
      renderArr.push(routes[i]);
    }
  }
  return renderArr;
}

/**
 * Get router routing configuration
 * { path:{name,...param}}=>Array<{name,path ...param}>
 * @param {string} path
 * @param {routerData} routerData
 */
export function getRoutes(path, routerData) {
  let routes = Object.keys(routerData).filter(
    routePath => routePath.indexOf(path) === 0 && routePath !== path
  );
  // Replace path to '' eg. path='user' /user/name => name
  routes = routes.map(item => item.replace(path, ''));
  // Get the route to be rendered to remove the deep rendering
  const renderArr = getRenderArr(routes);
  // Conversion and stitching parameters
  const renderRoutes = renderArr.map(item => {
    const exact = !routes.some(route => route !== item && getRelation(route, item) === 1);
    return {
      exact,
      ...routerData[`${path}${item}`],
      key: `${path}${item}`,
      path: `${path}${item}`,
    };
  });
  return renderRoutes;
}

// 判断是否为合法 Url
export function isUrl(path) {
  const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/g;
  return reg.test(path);
}

/** 根据出生日期计算年龄(yyyy-MM-dd) */
export function getBrithAge(birthday) {
  const nowDay = new Date();
  // 出生年月日
  const birthYear = birthday.getFullYear();
  const birthMonth = birthday.getMonth() + 1;
  const birthDate = birthday.getDate();
  // 当前年月日
  const nowYear = nowDay.getFullYear();
  const nowMonth = nowDay.getMonth() + 1;
  const nowDate = nowDay.getDate();

  // 计算年差
  let age = nowYear - birthYear;
  // 当前月小于出生月,则岁数不足
  if (nowMonth < birthMonth) {
    age -= 1;
  } else if (nowMonth === birthMonth) {
    // 当前日期小于出日期,则岁数不足
    if (nowDate < birthDate) {
      age -= 1;
    }
  }

  return age;
}

收集整理中...

标签:const,实用工具,JavaScript,return,item,moment,path,now,方法
From: https://www.cnblogs.com/yuzhihui/p/17041246.html

相关文章

  • javaScript Object.is和==和===
    ##相等运算符(==)==相等运算符在判断相等前对两边的变量(如果它们不是同一类型)进行强制转换1.如果操作数具有相同的类型,则按如下方式进行比较:-对象:`true`仅......
  • JavaScript 将base64 转换为File
    在JavaScript中,可以使用Blob对象将base64字符串转换为File对象。 方法一(推荐,但存在兼容性问题):首先,你需要从base64字符串中获取文件类型,然后将文件类型和......
  • python 使用函数名的字符串调用函数(4种方法)
    先看一个例子:>>>deffoo():print"foo">>>defbar():print"bar">>>func_list=["foo","bar"]>>>forfuncinfunc_list:func()TypeError......
  • 6-集成方法
    title:6-集成方法date:2021-01-1810:58:30permalink:/pages/26d211/......
  • python里的__call__()方法
    解释__call__方法是Python中类的特殊方法,当一个类的实例被“调用”时,就会自动触发这个方法。“调用”一个类的实例就是使用小括号()操作符。举个例子:classAdder:......
  • JavaScript 中URL 查询字符串(query string)的序列与反序列化
    方法一:在JavaScript中,可以使用URLSearchParams对象来处理URL中的查询字符串。序列化(将JavaScript对象转换为查询字符串)可以使用URLSearchParams对象的append(......
  • 世上最强学习方法——费曼学习法(深度学习)
    世上最强学习方法——费曼学习法(深度学习)费曼学习法的核心要义是通过复述概念并反馈结果来加强记忆。 一、选择目标领域,并完全了解这个概念将需要学习的概念写在纸上,......
  • JavaScript 计算base64编码图片大小
    JavaScript可以通过获取图片的base64编码并计算其大小来计算图片大小。方法一://计算base64编码图片大小functiongetBase64ImageSize(base64){ if(base64){ b......
  • 学习-Vue2-Vue实例-数据与方法-数据的响应式
    当一个实例被创建时,它将data对象中的所有的property加入到Vue的响应式系统中。当这些property的值发生改变时,视图将会产生“响应”,即匹配更新为新的值。当这些数据改变时,......
  • Java学习方法
    如何更好的学习方法多写代码,多写笔记,多写文章多练交流,多练思维,多练技能多分享,多提问,多思考学习准备:博客为什么要写博客?需要思考和总结提升文笔组织能力提升学习......