最近一直宅在家里,回头看看问题解闷。今天总结一下一年来使用的工具(github开源仓库,请勇敢star),顺便发一个npm包:haUtil数据处理,更详细的浅拷贝和深拷贝分析,请查看:清晰易懂!解释JS赋值、浅拷贝和深拷贝Shallowcopy/***Shallowcopy*@param{Object}source*@returns{Object}*/functionclone(source){constresult=Object.assign({},source);返回结果;}module.exports=克隆;deepcopy深拷贝的原理是一层层遍历,直到所有的数据都无法探索为止/***deepcopy*@param{*}source*@param{WeakMap}weakMap*@returns{*}target*///可遍历对象constiterations=['[objectObject]','[objectArray]','[objectMap]','[objectSet]',];functioncloneDeep(source,weakMap=newWeakMap()){if(source===null)返回源;//获取对象类型consttype=Object.prototype.toString.call(source);//处理不可遍历的对象if(!iterations.includes(type)){if(type==='[objectDate]')returnnewDate(source);if(type==='[objectRegExp]')returnnewRegExp(source);if(type==='[objectSymbol]')returnSymbol(source.description);if(type==='[objectFunction]')返回源;//剩下的一般就是原来的类型,直接返回ret骨灰盒来源;}//创建目标实例lettarget=newsource.constructor();//{}|[]|地图(0)|Set(0)//处理循环调用constval=weakMap.get(source);如果(val)返回val;weakMap.set(源,目标);if(type==='[objectMap]'){source.forEach((value,key)=>{target.set(key,cloneDeep(value));});返回目标;}if(type==='[objectSet]'){source.forEach(value=>{target.add(cloneDeep(value));});返回目标;}//Processobjectsandarraysfor(constkeyinsource){target[key]=cloneDeep(source[key],weakMap);}returntarget;}module.exports=cloneDeep;任意范围的随机数/***生成指定范围内的随机数[min,max]*@param{Number}min*@param{Number}max*@return{Number}*/functionrandomNum(min,max){如果(最小值>=最大值)返回最小值;min=Math.ceil(min);max=Math.floor(max);返回Math.floor(Math.random()*(max-min+1))+min;}module.exports=randomNum;numbertopercentage/***转换百分比*@param{number}num*@param{number}total*@returns{string}percentage*/functiontoPercent(num,total){让str=num>=0&&total>0?Number(((num/total)*100).toFixed(2)):0;返回str;}module.exports=toPercent;fileunitadaptation/***filesizeunitadaptation,自动转换B,K,M,G单位*@param{number|string}fileSize文件大小,在B*@returns{string}*/functiontranslateFileSize(fileSize){if(fileSize===null||typeoffileSize==='undefined'||fileSize===''){return'—';}if(fileSize<1024){fileSize=fileSize+'B';}elseif(fileSize<1024*1024){fileSize=Math.floor((fileSize*10)/1024)/10+'K';}elseif(fileSize<1024*1024*1024){fileSize=Math.floor((文件大小*10)/(1024*1024))/10+'M';}else{文件大小=数学。floor((fileSize*10)/(1024*1024*1024))/10+'G';}returnfileSize;}module.exports=translateFileSize;amount处理金额超过三位加逗号/***金额超过三位加','*@param{string}numAmount*@param{string}locales本地化配置,默认zh-CN*@param{object}options本地化配置,默认{style:'currency',currency:'CNY'}*@returns{string}*/functionamountFormat(num,locales='zh-CN',options={style:'currency',currency:'CNY'}){返回数字?Number(num).toLocaleString(locales,options):'0';}module.exports=amountFormat;事件处理anti-shake/***anti-shake**Usage:*constcbFun=debounce(fun,2000)*cbFun()*/functiondebounce(fn,delay=1000){lettimer=null;returnfunction(){if(timer!==null){clearTimeout(timer);}timer=setTimeout(()=>{fn.apply(this,arguments);},delay);};}module.exports=debounce;throttle/***throttle**用法:*constcbFun=throttle(fun,2000)*cbFun()*/functionthrottle(fn,delay=1000){letold=0;returnfunction(){letnow=newDate().valueOf();if(now-old>delay){fn.apply(this,arguments);旧=现在;}};}module.exports=油门;timervarrequestAnimFrame=(function(){返回(window.request动画帧||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||函数(回调){window.setTimeout(回调,1000/60);});})();/***rAF定时器**用法:*constcbFun=rafInterval(fun,2000)*cbFun()*/functionrafInterval(fn,delay=1000){letstart=0;functionfun(){consttimestamp=newDate().valueOf();如果(开始===未定义)开始=时间戳;如果(时间戳-开始>延迟){开始=时间戳;fn.apply(这个,参数);}requestAnimFrame(乐趣);}returnfunction(){requestAnimFrame(fun);};}module.exports=rafInterval;文件处理导出文件/***导出文件*@param{string}biteData字节流*@param{string}标题文件名*@param{string}ext文件后缀*/functiondownloadFile(biteData,title='Export',ext='xls'){letblob=newBlob([biteData],{type:'application/octet-binary'});让downloadElement=document.createElement('a');让href=window.URL.createObjectURL(blob);下载元素.target='_blank';下载元素.href=href;downloadElement.download=`${title}.${ext}`;//文件名document.body.appendChild(downloadElement);下载元素.click();document.body.removeChild(downloadElement);window.URL.revokeObjectURL(href);//释放blob对象}module.exports=downloadFile;jsonexportcsvfile/***JSON数据转CSV文件export*@param{Array}列出要导出的JSON数据*@param{Array}colsheadername,theformatis:['ID','Name','Gender'],默认使用第一个数据的key*@param{Array}keysheader中使用的key,格式为:['id','name','gender'],需要和cols一一对应,否则导出数据有问题,默认使用第一个数据的key*@param{string}fileName导出的文件名,不带日期前缀和文件类型后缀**用法:*json2Csv(list,cols,keys,fileName)*/functionjson2Csv(list,cols,keys,fileName='datadetails'){if(!(listinstanceofArray&&colsinstanceofArray&&keysinstanceofArray&&typeoffileName==='string')){console.log('参数格式错误');返回;}如果(list.length===0)返回;如果(列长度h===0)cols=Object.keys(list[0]);如果(keys.length===0)keys=Object.keys(list[0]);文件名=文件名||'数据明细';让标题=列;让jsonKey=键;让数据=列表;让str=[];str.push(title.join(',')+'\n');for(leti=0;i
