常用utils.js 后续完善

6,135 阅读2分钟

获取hash搜索参数

const getHashSearchParam = (key) => {
  const search = /(?<=#.*\?).*/.exec(location.href)?.[0]
  const params = new URLSearchParams(search)
  return params.get(key)
}

调用:getHashSearchParam('name') => 'hash模式(#)下url的name参数值'

获取搜索参数

const getSearchParam = (key) => {
  return new URLSearchParams(location.search).get(key)
}

调用:getSearchParam('name') => 'url的name参数值'

小时差或分钟差:计算小时差值,小时差值转分钟

const calcHourDiff = (start, end) => {
    const [startHour, startMinutes] = start.split(':')
    const [endHour, endMinutes] = end.split(':')
    const diffMinutes = (new Date(null, null, null, endHour, endMinutes) -
        new Date(null, null, null, startHour, startMinutes)) / (60 * 1000)
    const diffHours = Math.round((diffMinutes / 60) * 100) / 100
    return {
            minutes: diffMinutes,
            hours: diffHours,
    }
}

调用:calcHourDiff('12:00', '12:56') => { "minutes": 56, "hours": 0.93 }

字符串:'-'连接命名转换成小驼峰命名

const _toLittleCamel =(str) => {
    if(!str) return ''
    return str.replace(/-(\w)/g, (_, code) => (code ? code.toUpperCase() : ""))
}

调用:_toLittleCamel('hello-world') => helloWorld

字符串:'-'连接命名转换成大驼峰命名

const _toBigCamel = (str) => {
        if (!str) return ''
        return str
                .replace(/-(\w)/g, ($0, $1) => $1.toUpperCase())
                .replace(/\S/, (code) => code.toUpperCase())
}

调用:_toBigCamel('hello-world') => HelloWorld

字符串:驼峰命名转换成'-'连接命名

const camelTo_ = (str) => {
        if (!str) return ''
        return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()
}

调用:camelTo_('HelloWorld') => hello-world

笛卡尔积算法 计算商品SKU集合

const cartesian = (input) => {
        const entries = Object.entries(input || {})

        let products = []
        entries.forEach((entry) => {
                products = cartesianProduct(entry, products)
        })

        return products
}

const cartesianProduct = (item, currentProducts) => {
        console.log(item, currentProducts)
        const itemKey = item[0]
        const itemValue = item[1]
        const _currentProducts = currentProducts || []

        if (Object.keys(_currentProducts).length <= 0) {
                return itemValue.map((value) => ({
                        [itemKey]: value,
                }))
        }

        const products = []

        Object.keys(itemValue).forEach((key) => {
                _currentProducts.forEach((product) => {
                        products.push({
                                ...product,
                                [itemKey]: itemValue[key],
                        })
                })
        })

        return products
}

调用:cartesian({ color: ['黑色', '白色', '金色'], storage: ['64', '128', '256', '512'], size: ['5.5', '6.5', '7.5'], brand: ['Apple', 'Huawei', 'Mi', 'vivo'] }) => [{color: '黑色', storage: '64', size: '5.5', brand: 'Apple'},...] 144条数据

数值单位转换

const numberUnitFormat =(value) => {
            let param = {};
            let k = 10000;
            let sizes = ['', '万', '亿', '万亿'];
            let i = null;
            if (value < k) {
                param.value = value;
                param.unit = '';
            } else {
                i = Math.floor(Math.log(value) / Math.log(k));
                param.value = (value / Math.pow(k, i)).toFixed(2);
                param.unit = sizes[i];
            }
            return param;
        }

调用:numberUnitFormat(23232323343.23) => { "value": "232.32", "unit": "亿" }

千分位转换

const thousandFormat = (num, obj) => {
            let param = '';
            if (!obj) {
                //格式化千分位输出
                param = num.toLocaleString();
            } else if (obj && obj.lang === 'en') {
                //格式化为千分位带$符号输出
                param = num.toLocaleString('en', { style: 'currency', currency: 'USD' });
            } else if (obj && obj.lang === 'cn') {
                //格式化为带¥符号输出
                param = num.toLocaleString('cn', { style: 'currency', currency: 'CNY' });
            } else {
                //格式化千分位输出
                param = num.toLocaleString();
            }
            return param;
        }

调用:thousandFormat(123456789.0, { lang: 'cn' }) => ¥123,456,789.00

千分位转数值:num.replace(/,/gi,'')

分转元

const convertCentToYuan = (cent) => {
    const tempArr = cent.toString().padStart(3, '0').split('');
    tempArr.splice(-2, 0, '.');
    return tempArr.join('');
}

调用:convertCentToYuan(100000) => 1000

数组列表转树形结构1

# 1w条数据,平铺数组转树形结构

const arrayToTree = (items, childName = 'children') => {
    const result = []; // 存放结果集
    const itemMap = {}; //
    for (const item of items) {
            const id = item.id;
            const pid = item.parentId;

            if (!itemMap[id]) {
                    itemMap[id] = {
                            [childName]: [],
                    };
            }
            itemMap[id] = {
                    ...item,
                    [childName]: itemMap[id][childName],
            };

            const treeItem = itemMap[id];

            if (pid === 0) {
                    result.push(treeItem);
            } else {
                    // if (!itemMap[pid]) {
                    // 	itemMap[pid] = {
                    // 		[childName]: [],
                    // 	};
                    // }
                    itemMap[pid][childName].push(treeItem);
            }
    }
    return result;
}

调用:arrayToTree(data) => 返回树形数组

数组列表转树形结构2

# 扁平数组与JSON树结构互转

const listToTree = (list, childName = 'children') => {
    const res = [];
    const map = list.reduce((res, v) => ((res[v.id] = v), res), {});

    for (const item of list) {
            if (item.parentId === 0) {
                    res.push(item);
                    continue;
            }
            if (item.parentId in map) {
                    const parent = map[item.parentId];
                    parent[childName] = parent[childName] || [];
                    parent[childName].push(item);
            }
    }
    return res;
}

调用:listToTree(data) => 返回树形数组

树形结构转扁平数组列表

const treeToList = (data, childName = 'children') => {
    // if (!Array.isArray(data)) {
    // 	return [];
    // }
    return data.reduce(
        (prev, cur) =>
            prev.concat([cur], treeToList(cur[childName] || [])),
        []
    );
};

调用:treeToList(data) => 返回扁平数组列表

数组去重

/**
 * 如果是纯粹数组,用es6 Set去重,只需要传arr即可
 * @param  {} arr 数组 or 对象数组
 * @param  {} params 数组对象去重时根据key值去重
 */
const uniq = (arr, params) => {
	if (!Array.isArray(arr)) {
		return arr;
	}
	if (params) {
		let obj = {};
		let newArr = arr.reduce((perv, cur) => {
			obj[cur[params.key]]
				? ''
				: (obj[cur[params.key]] = true && perv.push(cur));
			return perv;
		}, []);
		return newArr;
	} else {
		return Array.from(new Set(arr));
	}
};

调用:uniq(data, { key: 'id' }) => 返回根据ID去重后的对象数组列表

对象数组去重

/**
 * 数组的对象完全匹配后去重
 * @param  {} data 对象数组
 */
const uniqObject = (data) => {
	let uniques = [];
	let stringify = {};
	for (let i = 0; i < data.length; i++) {
		let keys = Object.keys(data[i]);
		keys.sort(function (a, b) {
			return Number(a) - Number(b);
		});
		let str = '';
		for (let j = 0; j < keys.length; j++) {
			str += JSON.stringify(keys[j]);
			str += JSON.stringify(data[i][keys[j]]);
		}
		if (!stringify.hasOwnProperty(str)) {
			uniques.push(data[i]);
			stringify[str] = true;
		}
	}
	uniques = uniques;
	return uniques;
};

调用:uniqObject(data) => 返回去重后的对象数组列表