风吹夏天 2020-07-04
缓存优化查询
const fs=require(‘fs‘); //比较字符基类大小 相同返回0,str1>str2 返回1,str1<str2 返回-1, function str_compare(str1,str2){ let index=0; let dis=0; while (dis===0&&index<str1.length){ if(str1.charCodeAt(index)>str2.charCodeAt(index)){ dis=1 }else if(str1.charCodeAt(index)<str2.charCodeAt(index)){ dis=-1 }else{ index++; if(index>str2.length){ dis=1; } } } if(dis===0&&index<str2.length){ dis=-1 } return dis; } //查找 function find(str,hasSortArr,callback) { let l=0,r=hasSortArr.length; let index=-1; if(hasSortArr.length>0){ const ri=callback(str,hasSortArr[r-1]); if(ri===1){ return [r,-1] }else if(ri===0){ return [r-1,r-1] }else{ r=r-1; } const li=callback(str,hasSortArr[0]); if(li===-1){ return [0,-1] }else if(li===0){ return [0,0] }else{ l=l+1; } while(r-l>0){ const m=(l+r)>>1; //比较下坐标大小 const order=callback(str,hasSortArr[m]) if(order===1){ l=Math.max(l+1,m) }else if(order===-1){ r=Math.min(r-1,m) }else{ l=r=m; index=m; } } } return [(l+r)>>1,index] } //输入排名函数,返回-1,0,1 function sort(list,compare){ const hasSortArr=[] for(let i=0;i<list.length;i++){ const [n,index]=find(list[i],hasSortArr,compare) //增加、插入 hasSortArr.splice(n,0,list[i]) } return hasSortArr; } /* demo 文件内容排名算法,输入排名函数,返回排名后的文件名 */ const dir=__dirname+‘/data/‘; const list=fs.readdirSync(dir); //用缓存优化查询 let cacheArr=[] const cacheLen=10; const hasSortArr=sort(list,function (name1,name2) { let index1=-1; let index2=-1; for(let i=0;i<cacheArr.length;i++){ if(index1===-1&&cacheArr[i].name===name1){ index1=i; } if(index1===-1&&cacheArr[i].name===name2){ index2=i; } if(index1!==-1&&index2!==-1){ break; } } let n1=index1; let n2=index2; if(index1===-1){ const val=fs.readFileSync(dir+name1).toString() cacheArr.unshift({ name:name1, val:val, time:Date.now() }) n1=0; } if(index2===-1){ const val=fs.readFileSync(dir+name2).toString() cacheArr.unshift({ name:name2, val:val, time:Date.now() }) n1++; n2=0; } const cont1=cacheArr[n1].val; const cont2=cacheArr[n2].val; //清理 if((index1===-1||index2===-1)&&cacheArr.length>cacheLen){ cacheArr.splice(cacheLen,cacheArr.length-cacheLen) } return str_compare(cont1,cont2) }) console.log(hasSortArr)