/**
* 将参数格式化为对象
* @param urlParams type string
* @example
* let urlParams = 'name="xiaoliu"&age=20&sex="男"'
* getUrlObject(urlParams)
* @returns
* {
* name:"xiaoliu",
* age:20,
* sex:"男",
* }
*/
1 export const getUrlObject = (urlParams) => {
2 try {
3 if (typeof urlParams !== 'string') return;
4 return urlParams.split('&').reduce((prev, curr) => {
5 curr = curr.split('=');
6 return Object.assign(prev, {[curr[0]]: curr[1]});
7 }, {});
8 } catch (err) {
9 throw new Error(`${err}in getUrlObject`);
10 }
11 };
/**
* 替换url上的匹配字段
* @param url @type string 需要替换的url
* @param data @type object 代替换的数据参数
* @example
* let url = 'ceshi/url/delete/^.^{id}';
* let data = {id:2};
* @returns 'ceshi/url/delete/2'
*/
export const formatUrl = (url, data) => {
try {
return url.replace(/^.^{(w+)}/g, function (match, key) {
return data[key];
});
} catch (err) {
throw new Error(`${err}in formatUrl`);
}
};
/**
* 从源数据中替换指定内容为指定模板
* @param template 模板中需要指定特殊字符串(^.^{VALUE})用来替换匹配到的值(replaceVal)
* @param replaceVal 需要替换的内容
* @param sourceVal //源数据
* @example
* let template = '<span style="color: red">^.^{VALUE}</span>';
* let replaceVal = '替换';
* let sourceVal = '这个是替换匹配值的方法'
* replaceTemplate (template, replaceVal, sourceVal)
* @returns 这个是<span style="color: red">替换</span>匹配值的方法
*/
export const replaceTemplate = (template, replaceVal, sourceVal) => {
if (!replaceVal) return sourceVal;
return sourceVal.replace(new RegExp(replaceVal, 'g'), (match) => {
return template.replace(/^.^{VALUE}/, () => {
return match;
});
});
};
/**
* 从数组对象中获取给定参数的值得数组集合
* @param params @type Array|String 需要收集的参数列表
* @param list @type Array 源列表数据
* @example
* let params = ['id','name']
* let list = [{id:1,name:'xiaoming',desc:'ceshi'},{id:2,name:'xiaozhang',desc:'ceshi2'}]
* getParamsArray(params, list)
* @returns [[1,2],['xiaoming','xiaozhang']]
*/
export const getParamsArray = (params = [], list = []) => {
try {
params = Array.isArray(params) ? params : [params];
return list.reduce((a, b) => {
return params.map((name, index) => {
return (a[index] || []).concat(b[name] || [0]);
});
}, []);
} catch (err) {
throw new Error(err);
}
};
/**
* 返回两个数组的交集
* @param arr1
* @param arr2
*/
export const arraryIntersect = (arr1 = [], arr2 = []) => {
return arr1.filter(v => {
return arr2.includes(v);
});
};
/**
* 格式化字节
* @param value @type number 字节大小
* @param unit @type string 字节单位
* @example
formatByte(1024*1024,'Bytes');
* @returns {value:1024,unit:'KB'}
*/
export const formatByte = (value, unit = 'Bytes') => {
try {
let UNITCOLLECTION = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
let data = {
value: value,
unit: unit
};
UNITCOLLECTION = UNITCOLLECTION.slice(UNITCOLLECTION.indexOf(unit) + 1);
while (data.value > 1024 && UNITCOLLECTION.length > 0) {
data.value = data.value / 1024;
data.unit = UNITCOLLECTION.splice(0, 1)[0];
};
return data;
} catch (err) {
throw new Error(`${err}in formatUrl`);
}
};
Bytes