/* eslint-disable @typescript-eslint/no-var-requires */ /* eslint-disable no-param-reassign */ import { App } from './types'; import { isString, isSymbol, isNumber, isObject, isEmpty, } from './isType'; const projectConfig = require('configure/projectConfig.json'); // Array转Map const listToMap = (list: App.Option[]) => { const map: App.Dict = {}; for (let i = 0, len = list.length; i < len; i += 1) { map[list[i].value] = list[i].label; } return map; }; // 生成随机数 const getRandom = (o: number, n: number | null) => { if (n === null) { n = o; o = 0; } return o + Math.floor(Math.random() * (n - o + 1)); }; // 由object生成url参数 const transformRequest = (obj: { [key: string]: any }) => { const str: string[] = []; if (obj) { Object.keys(obj).forEach((key) => { str.push(`${encodeURIComponent(key)}=${encodeURIComponent(isEmpty(obj[key]) ? "" : obj[key])}`); }); } return str.join('&'); }; // 获取制定url参数 const getSearchParam = (name: string) => { if (!window.location.search && !window.location.hash) { return ''; } const searchParams = window.location.search.replace('?', '').split('&'); const hashParams = (window.location.hash.split('?').length > 1 ? window.location.hash.split('?')[1] : '').split('&'); const params = [...searchParams, ...hashParams]; const json: App.Dict = {}; for (let i = 0; i < params.length; i += 1) { if (params[i]) { const arr = [...params[i].split('=')]; const zero = 0; const one = 1; json[arr[zero]] = arr[one]; } } if (/^\d+$/.test(json[name])) { return parseInt(json[name], 10); } return json[name]; }; /** * getSearchParam 获取url search全部 * @param {searchStr} searchStr searchStr * @returns {*} * */ const getSearchParams = (url?: any) => { const search = url ? new URL(`http:/${url}`).search : window.location.search; const hash = url ? new URL(`http:/${url}`).hash : window.location.hash; if (!search && !hash) { return {}; } const searchParams = search.replace('?', '').split('&'); const hashParams = (hash.split('?').length > 1 ? hash.split('?')[1] : '').split('&'); const params = [...searchParams, ...hashParams]; const json: App.Dict = {}; for (let i = 0; i < params.length; i += 1) { if (params[i]) { const arr = [...params[i].split('=')]; const zero = 0; const one = 1; json[arr[zero]] = arr[one]; } } return json; }; // 根据value获取label const findLabel = (value: string | number | number, list?: App.Option[]) => { if (!list) { return value; } const target = list.find((item: App.Option) => { return item.value === value || value === undefined && item.value === "undefined"; }); return target ? target.label : ''; }; const getItemByValue = (obj: any[], name: string, value: string | number) => { if (!obj) { return {}; } const target = obj.find((item) => item[name] === value); return target || {}; }; const toKey = (value: number) => { if (isString(value) || isSymbol(value)) { return value; } const result = `${value}`; return result === '0' && 1 / value === -Infinity ? '-0' : result; }; // 根据路径获取object中的某个值 const getByPath = (object: { [key: string]: any }, path: string | any[]) => { let index = 0; let isBasics = false; if (isString(path)) { path = (path as string).split(/[\s,.]+/g); } else if (isNumber(path)) { path = [path]; } if (!Array.isArray(path)) { throw new Error('The types of path must be a string or a number or an array '); } const len = path.length; while (object !== null && index < len) { const current = object[toKey(path[index += 1])]; if (isObject(current) || Array.isArray(current)) { object = current; } else { isBasics = true; break; } } return { object, path, isBasics, // 是否是普通类型(不是引用类型) }; }; // 获取实际长度、英文及英文标点长度、字节长度 const getFormValueLen = ( val: string, rule = { min: 0, }, ) => { const value = val.trim(); const totalLen = value.length; // eslint-disable-next-line no-control-regex const noZHCNLen = value.replace(/[^\x00-\xff]/g, '').length; // bLen 字节长度 const bLen = noZHCNLen / 2 + totalLen - noZHCNLen; let len = Math.ceil(bLen); if (rule.min > 1 && bLen === rule.min - 0.5) { len -= 1; } return { totalLen, noZHCNLen, // 英文及英文标点长度 showLen: len, // 字节长度 和最大值比较时向上区整,和最小值比较时向下取整 }; }; const encodeAttr = (str: string) => str .split('&') .join('&') .split('<') .join('<') .split('>') .join('>') .split('"') .join('"'); const decodeAttr = (str: string) => (str ? str.replace(/&((g|l|quo)t|amp|#39|apos);/g, (m: string): string => { if (!m) return ''; const codeMap: App.Dict = { '<': '<', '&': '&', '"': '"', '>': '>', ''': "'", ''': "'", }; return codeMap[m]; }) : ''); const uniqueArr = (arr: string | any[]) => { const res = []; const json: App.Dict = {}; for (let i = 0; i < arr.length; i += 1) { if (!json[arr[i]]) { res.push(arr[i]); json[arr[i]] = 1; } } return res; }; const stringifyAttrs = (attrs: { [x: string]: any } | null | undefined) => { if (attrs === null || attrs === undefined) { return ''; } const parts: string[] = []; Object.keys(attrs).forEach((name) => { const value = attrs[name]; if (value !== null && value !== undefined) { parts.push(` ${name}="${encodeAttr(`${value}`)}"`); } }); return parts.join(''); }; const platArr = (arr: any[]) => arr.reduce((a: string | any[], b: any) => a.concat(b)); const upperFirstLetter = (word: string) => word.charAt(0).toUpperCase() + word.slice(1); const lowerFirstLetter = (word: string) => word.charAt(0).toLowerCase() + word.slice(1); const stringifyUrlSearch = (url: any) => { const searchObj: App.Dict = {}; const searchStr = (url || window.location.href).split('?')[1]; if (searchStr) { decodeURIComponent(searchStr) .split('&') .forEach((item) => { const searchItem = item.match(/([^=]+)=([^]+)/); if (searchItem) { const [key, val] = searchItem; searchObj[key] = val; } }); } return searchObj; }; const switchArrToStr = (arr: string[], mark = ','): string => arr.join(mark); const formatObjBySwitchArrToStr = (obj: App.Dict, mark: string) => { const formatedObj: App.Dict = {}; Object.keys(obj).forEach((item: string) => { if (Array.isArray(obj[item])) { formatedObj[item] = switchArrToStr(obj[item], mark); } else { formatedObj[item] = obj[item]; } }); return formatedObj; }; const formatObjByDeleteEmptyStr = (obj: App.Dict) => { const formatedObj: App.Dict = {}; Object.keys(obj).forEach((item: string) => { if (!isEmpty(obj[item])) { formatedObj[item] = obj[item]; } }); return formatedObj; }; const setDefaultValue = (value: any) => { switch (value) { case null: return projectConfig.nullLabel !== undefined ? projectConfig.nullLabel : null; case undefined: return projectConfig.undefinedLabel !== undefined ? projectConfig.undefinedLabel : undefined; case '': return projectConfig.emptyLabel !== undefined ? projectConfig.emptyLabel : ''; default: return value; } }; const parseData2Url = ( ajaxData: App.Dict, ajaxUrl: string, accept: [], rule: (string | { [key: string]: any })[], ) => { const data = JSON.parse(JSON.stringify(ajaxData)) || {}; let url = ajaxUrl || ''; for (let i = 0; i < (rule || []).length; i += 1) { if (url.indexOf('#{key}') === -1) { // console.error(`${ajaxUrl}缺少关键字#{key}!`); break; } if (typeof rule[i] === 'string') { const schema = rule[i] as string; if (!schema) { // console.error(`${ajaxUrl}的请求参数缺少${schema}!`); break; } url = url.replace('#{key}', data[schema]); delete data[rule[i] as string]; } else if (typeof rule[i] === 'object' && (rule[i] as App.Dict).key) { const schema = rule[i] as App.Dict; if (data[schema.key] === undefined || data[schema.key] === null || data[schema.key] === '') url = url.replace('#{key}', schema.default); else url = url.replace('#{key}', data[schema.key]); delete data[schema.key]; } } if (url.indexOf('#{key}') > -1) { // console.error(`${ajaxUrl}多余关键字#{key}/缺少给定变量!`); } if (!accept.length) { return { data, url, }; } const acceptData: App.Dict = {}; for (let j = 0; j < accept.length; j += 1) { acceptData[accept[j]] = data[accept[j]]; } return { data: acceptData, url, }; }; const parseUrlTemplate = (url: string, data: App.Dict): string => { if (!url) return ''; const parsedUrl = url.replace(/#\{(\w+)\}/g, (m, m1): string => data[m1]); return parsedUrl; }; function formatToNumber(strParam: number, pointParam?: any) { let str = `${strParam}`; let point = pointParam; if (str === 'NaN' || str === 'Infinity') { return '--'; } if (point === undefined || point === null) point = 4; if (parseFloat(str) === 0) return parseFloat(str); if (parseFloat(str) < 1) return parseFloat(str).toFixed(point); let pn = ''; if (str.indexOf('.') > -1) { pn = str.substr(str.indexOf('.'), str.length); str = str.substr(0, str.indexOf('.')); } let len = str.length; let str2 = ''; const max = Math.floor(len / 3); for (let i = 0; i < max; i += 1) { const s = str.slice(len - 3, len); str = str.substr(0, len - 3); str2 = `,${s}${str2}`; len = str.length; } str += str2; if (str.indexOf(',') === 0) str = str.substr(1, str.length); return str + pn.substr(0, 3); } export { listToMap, getRandom, transformRequest, getSearchParams, getSearchParam, findLabel, getItemByValue, getByPath, getFormValueLen, encodeAttr, decodeAttr, uniqueArr, platArr, upperFirstLetter, lowerFirstLetter, stringifyUrlSearch, stringifyAttrs, switchArrToStr, formatObjBySwitchArrToStr, formatObjByDeleteEmptyStr, setDefaultValue, parseData2Url, parseUrlTemplate, formatToNumber, };