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) => {
if (pathRegexp(`${route.path}/(.*)`).test(`${path}/`)) {
if (route.authority) {
authorities = route.authority;
}
if (route.path === path) {
authorities = route.authority || authorities;
}
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);
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;
};
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 }) => {
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) => {
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 };
});
};
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 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));
}
return data.reverse();
};
export const getUrlProps = (url: any) => {
const str: any = url.slice(url.indexOf("?") + 1);
let arr = str.split("&");
let obj: any = {};
for (let i = 0; i < arr.length; i++) {
let newArr: any = arr[i].split("=");
obj[newArr[0]] = newArr[1];
}
return obj;
};
export const formatStartData = (val) => {
if (val) {
return moment(val).startOf("day").unix().toString();
}
return "";
};
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 ? "千万" : "万";
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;
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));
};