js常用工具函数

js常用工具函数

生成随机数 @param {} min 最小位数 @param {} max 最大位数

javascript

function randomString(min=7, max=15){
    let str = "",
        range = min,
        arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
 
    // 随机产生
    range = Math.round(Math.random() * (max-min)) + min;
    for(var i=0; i<range; i++){
        var pos = Math.round(Math.random() * (arr.length-1));
        str += arr[pos];
    }
    return str;
}
// 数组去重,type 为数组的唯一标识 array:[{id: 1, name: "jason"}]
function uniqueData(arr, type) {
    if (!Array.isArray(arr)) {
        return;
    }
    for(var i=0; i<arr.length; i++){
        for(var j=i+1; j<arr.length; j++){
            if(arr[i][type]==arr[j][type]){  //第一个等同于第二个,splice方法删除第二个
                arr.splice(j,1);
                j--;
            }
        }
    }
    return arr;
}
// 实现首字母大写
function firstUpperCase(word){
	if(typeof word!=="string") return word;
	return word.replace(/\b(\w)(\w*)/g, function($0, $1, $2) {
        return $1.toUpperCase() + $2.toLowerCase();
    });
}
// 判断是否有class名称
function hasClass(obj, cls) {
    return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
 // 添加calss名称
 function addClass(obj, cls) {
    if (!hasClass(obj, cls)) {
        obj.className += " " + cls;
    }
}
 // 移除class名称
function removeClass(obj, cls) {
    if (hasClass(obj, cls)) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        obj.className = obj.className.replace(reg, ' ');
    }
}
 // 切换class名称
 function toggleClass(obj,cls){
    if(hasClass(obj,cls)){
        removeClass(obj, cls);
    } else {
        addClass(obj, cls);
    }
}
// 深拷贝
function cloneDeep(value){
	return JSON.parse(JSON.stringify(value));
}

// 获得某月的天数
function getMonthDays(nowYear, month){
    let monthStartDate = new Date(nowYear, month, 1);
    let monthEndDate = new Date(nowYear, month + 1, 1);
    let days = (monthEndDate - monthStartDate)/(1000 * 60 * 60 * 24);
    return days;
}

/**
 * 高阶函数,封装某个api方法,返回一个新方法,此新方法可以将返回的数据存到localStorage
 * @param {function} api fn
 * @param {string} fnName
 * @param {string} option.type   sessionStorage:存在sessionStorage里  localStorage:存在localStorage里
 * @param {number} option.expire   过期日长 默认1小时(1*60*60*1000)
 * @return {function} new api fn
 */
function withStorageCache(fn,fnName="",option={}){
	option = Object.assign({},{
		type:"sessionStorage",
		expire:1*60*60*1000
	},option);
	fnName = fnName || fn.name;
	const {type,expire} = option;
	const KEY = `AJAX_API_STORAGE_${fnName}`;
    const outputFn = function(...args) {
        const key = args.map((arg) => {
            if (isArray(arg) || isObject(arg)) {
                return qs.stringify(arg);
            } else {
                return arg;
            }
        }).join("&");
        let allStorage = type==="sessionStorage" ? sessionStorage.getItem(KEY) : localStorage.getItem(KEY);
        if(allStorage){
			allStorage = JSON.parse(allStorage);
			const storageRes = allStorage[key];
			if(storageRes){
				const {storage,time} = storageRes;
				const now = new Date().getTime();
				if(time && (now-time)<expire){ //缓存还未过期
					return Promise.resolve(cloneDeep(storage));
				}
			}
        }
        return fn.apply(null, args).then((res) => {
            const {code} = res;
            if(code==200){
				const now = new Date().getTime();
                try{
					//把数据存进localStorage或sessionStorage;
					allStorage = allStorage || {};
					const storageRes = {storage:res,time:now};
					allStorage[key] = storageRes;
					const str = JSON.stringify(allStorage);
					if(type==="sessionStorage"){
						sessionStorage.setItem(KEY,str)
					}else{
						localStorage.setItem(KEY,str);
					}
                }catch(e){
                    console.error(e);
                }
            }
            return res
        })
	}
	outputFn.cache = {
		clear : function(){
			type==="sessionStorage" ? sessionStorage.removeItem(KEY) : localStorage.removeItem(KEY);
		}
	}
	return outputFn
}
/**
 * 
 * @param {function} fn 请求方法
 * @param {string} fnName 方法名
 * @param {number} time 缓存时间(以分钟为单位 默认5分钟)
 */
 function withMemeryCache(fn,fnName,time=5){
	let __cache__ = {};
	let last = 0;
	fnName = fnName || fn.name;
	if(typeof time!=="number") time = 5; //默认5分钟
	time = time * 60 * 1000; //转成毫秒数
    const outputFn = function(...args) {
        const KEY = `AJAX_API_MEMERY_CACHE_${fnName}_`;
        const key = KEY + args.map((arg) => {
            if (Array.isArray(arg) || isObject(arg)) {
                return qs.stringify(arg);
            } else {
                return arg;
            }
        }).join("&");
		const cache = __cache__[key];
		const now = new Date().getTime();
        if(cache){
			const dis = now - last;
			if(dis<=time){
				last = now;
				return Promise.resolve(cloneDeep(cache));
			}
			__cache__[key] = null;
			delete __cache__[key];
		}
		last = now;
        return fn.apply(null, args).then((res) => {
            if (res.code == 200) {
				__cache__[key] = res;
            }
            return res;
        });
	}
	outputFn.clearCache = () => {
		__cache__ = {};
		last = 0;
	}
	return outputFn;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值