React 封装的一些格式化数据的组件方法

React 封装的一些格式化数据的组件方法

import pathRegexp from "path-to-regexp";
import moment from "moment";
import { parse } from "querystring";

export const getRouteAuthority = (path: string, routeData: any) => {
  let authorities: string[] | string | undefined;
  routeData.forEach((route) => {
    // match prefix
    if (pathRegexp(`${route.path}/(.*)`).test(`${path}/`)) {
      if (route.authority) {
        authorities = route.authority;
      }
      // exact match
      if (route.path === path) {
        authorities = route.authority || authorities;
      }
      // get children authority recursively
      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  return authorities;
};

//取出对象值
const get = (p) => (o) => p.reduce((xs, x) => (xs && xs[x] ? xs[x] : null), o);

/**
 * format对象
 * @param fileNames value值为数组
 * */
export const formatObject = (target, fileNames) => {
  let obj = {};

  Object.keys(fileNames).map((item) => {
    let getValue = get(fileNames[item]);

    getValue(target);

    obj[item] = getValue(target);
  });

  return obj;
};

//删除空值对象
export const deleteEmptyKey = (params) => {
  Object.keys(params).map((item) => {
    if (!params[item]) {
      delete params[item];
    }
  });

  return params;
};

//展开routes
export const expandRoutes = (arr) =>
  (arr || []).reduce((routes, item) => {
    routes.push(item);

    return routes.concat(
      (item && item.routes && expandRoutes(item.routes)) || []
    );
  }, []);

//过滤面包屑导航
// export const filterBreadcrumb = ({ routes, path }) =>
//   (routes || []).filter((q) =>
//     q && q.path && path
//       ? eval(`/^${q && q.path ? q.path.replaceAll("/", "\\/") : ""}/`).test(
//           path
//         )
//       : false
//   );
export const filterBreadcrumb = ({ routes, path }) => {
  return (routes || []).filter((q) =>
    q && q.path && path ? path.indexOf(q.path) >= 0 && !q.hidden : false
  );
};

// 校验子页面是否存在
export const checkHasPage = ({ routes, path }) => {
  const arr = (routes || []).filter((q) =>
    q && q.path && path ? path === q.path : false
  );
  if (arr.length) {
    const obj = arr[0];
    return obj.demoImageUrl || "";
  }
  return "";
};

export const normalizeLink = (to: string, location = window.location) => {
  to = to || "";

  if (to && to[0] === "#") {
    to = location.pathname + location.search + to;
  } else if (to && to[0] === "?") {
    to = location.pathname + to;
  }

  const idx = to.indexOf("?");
  const idx2 = to.indexOf("#");
  let pathname = ~idx
    ? to.substring(0, idx)
    : ~idx2
    ? to.substring(0, idx2)
    : to;
  let search = ~idx ? to.substring(idx, ~idx2 ? idx2 : undefined) : "";
  let hash = ~idx2 ? to.substring(idx2) : location.hash;

  if (!pathname) {
    pathname = location.pathname;
  } else if (pathname[0] != "/" && !/^https?\:\/\//.test(pathname)) {
    let relativeBase = location.pathname;
    const paths = relativeBase.split("/");
    paths.pop();
    let m;
    while ((m = /^\.\.?\//.exec(pathname))) {
      if (m[0] === "../") {
        paths.pop();
      }
      pathname = pathname.substring(m[0].length);
    }
    pathname = paths.concat(pathname).join("/");
  }

  return pathname + search + hash;
};

// 获取下拉值
export const filterCategory = (category) => {
  // console.log("arr===", arr);
  const dictionarys = localStorage.getItem("dictionaryInfo") || "";
  const dictionaryInfo: any = dictionarys ? JSON.parse(dictionarys) : [];

  return dictionaryInfo
    .filter((f) => f.category === category)
    .map((m) => {
      return { ...m, label: m.name, value: m.code };
    });
};

// 获取相应key所对应value值
export const getCodeValue = (codes: any, key: any) => {
  if (codes && codes.length) {
    const obj = codes.find((f) => f.value === key) || {};
    return obj.label || "";
  } else {
    return "";
  }
};

// 时间戳转时间字符串
export const formatDate = (date, fmt = "") => {
  if (date) {
    return moment(date * 1000).format(fmt);
  }
  return "-";
};

// 时间戳转时间字符串
export const formatDatetime = (date, fmt = "") => {
  if (date) {
    return moment(date).format(fmt);
  }
  return "-";
};

const getDay = (day: any) => {
  var today = new Date();
  var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
  today.setTime(targetday_milliseconds);
  var tYear = today.getFullYear();
  var tMonth = today.getMonth();
  var tDate = today.getDate();
  tMonth = doHandleMonth(tMonth + 1);
  tDate = doHandleMonth(tDate);
  // return tYear+"-"+tMonth+"-"+tDate; //年月日
  return tMonth + "-" + tDate; //月日
};

const doHandleMonth = (month) => {
  var m = month;
  if (month.toString().length == 1) {
    m = "0" + month;
  }
  return m;
};

export const getDates = (e) => {
  let data: any = [];
  //拼接
  data.splice(0); //请控之前的数据
  for (let i = 0; i < e; i++) {
    data.push(getDay(-i)); //-i 代表之前  i代表将来
  }
  return data.reverse();
};

// 解析url
export const getUrlProps = (url: any) => {
  // "https://www.baidu.com/s?ie=utf-8&f=3&rsv_bp=0"
  const str: any = url.slice(url.indexOf("?") + 1); //结果:ie=utf-8&f=3&rsv_bp=0
  let arr = str.split("&"); //结果: ["ie=utf-8", "f=3", "rsv_bp=0"]
  let obj: any = {};
  for (let i = 0; i < arr.length; i++) {
    let newArr: any = arr[i].split("="); //结果:["ie", "utf-8"],["f", "3"],["rsv_bp", "0"]
    obj[newArr[0]] = newArr[1];
  }
  return obj;
};

// 开始时间 0时0分0秒
export const formatStartData = (val) => {
  if (val) {
    return moment(val).startOf("day").unix().toString();
  }

  return "";
};
// 结束时间 23时59分59秒

export const formatEndData = (val) => {
  if (val) {
    return moment(val).endOf("day").unix().toString();
  }

  return "";
};

//格式化时间-》字符串
export const formatTime = (val) => {
  if (val) {
    return moment(val).unix().toString();
  }

  return "";
};

// 时间戳转换
export const formatTimestamp = (val) => {
  if (val) {
    return moment(val).unix().toString();
  }

  return "";
};

export const getPageQuery = () => parse(window.location.href.split("?")[1]);

export const getUrl = async () => {
  const config = window.localStorage.getItem("configObject");
  const serviceUrl = config
    ? JSON.parse(config)
    : await fetch(`config.json?t=${new Date().getTime()}`).then((response) =>
        response.json()
      );
  !config &&
    window.localStorage.setItem("configObject", JSON.stringify(serviceUrl));

  return serviceUrl;
};

// 对象删除空值属性
export const delUndefined = (ob) => {
  for (let e in ob) {
    if (typeof ob[e] === "undefined" || ob[e] === null || ob[e] === "") {
      delete ob[e];
    } else if (ob[e].constructor === Object) {
      if (Object.keys(ob[e]).length === 0) {
        delete ob[e];
      } else {
        delUndefined(ob[e]);
      }
    } else if (ob[e].constructor === Array) {
      ob[e].map(function (seg) {
        if (typeof seg === "object") {
          delUndefined(seg);
        }
      });
    }
  }
  return ob;
};

// 获取相应标签下数量
export const getCounts = (list, name) => {
  if (list && list.length) {
    const obj = list.find((f) => f.name === name) || {};
    return obj.value || 0;
  } else {
    return 0;
  }
};

export const getTreeData = (data) => {
  return (data || []).map((m) => {
    const { name, routes, ...others } = m;
    if (routes) {
      return {
        title: name,
        key: others.id,
        value: others.id,
        children: getTreeData(routes),
        ...others,
      };
    } else {
      return {
        title: name,
        key: others.id,
        value: others.id,
        ...others,
      };
    }
  });
};

export const bigNumberTransform = (value) => {
  const newValue: any = ["", "", ""];
  let fr = 1000;
  let num = 3;
  let text1 = "";
  let fm = 1;
  while (value / fr >= 1) {
    fr *= 10;
    num += 1;
  }
  if (num <= 8) {
    // 万
    text1 = parseInt(String(num - 4)) / 3 > 1 ? "千万" : "万";
    // tslint:disable-next-line:no-shadowed-variable
    fm = text1 === "万" ? 10000 : 10000000;
    if (value % fm === 0) {
      newValue[0] = parseInt(String(value / fm)) + "";
    } else {
      newValue[0] = parseFloat(String(value / fm)).toFixed(2) + "";
    }
    newValue[1] = text1;
  } else if (num <= 16) {
    // 亿
    text1 = (num - 8) / 3 > 1 ? "千亿" : "亿";
    text1 = (num - 8) / 4 > 1 ? "万亿" : text1;
    text1 = (num - 8) / 7 > 1 ? "千万亿" : text1;
    // tslint:disable-next-line:no-shadowed-variable
    fm = 1;
    if (text1 === "亿") {
      fm = 100000000;
    } else if (text1 === "千亿") {
      fm = 100000000000;
    } else if (text1 === "万亿") {
      fm = 1000000000000;
    } else if (text1 === "千万亿") {
      fm = 1000000000000000;
    }
    if (value % fm === 0) {
      newValue[0] = parseInt(String(value / fm)) + "";
    } else {
      newValue[0] = parseFloat(String(value / fm)).toFixed(2) + "";
    }
    newValue[1] = text1;
  }
  if (value < 10000) {
    newValue[0] = value + "";
    newValue[1] = "";
  }
  return newValue.join("");
};

export const format = (value) => {
  return Number((Number(value || 0) * 100).toFixed(2));
};

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值