当前位置: 首页 > Web前端 > CSS

【每天一包0019】mem

时间:2023-03-30 18:13:46 CSS

[github地址:https://github.com/ABCDdouyae...]mem用于通过缓存相同输入的调用结果来加速连续的函数调用常见用法(支持基于promise的异步函数调用)constmem=require('mem');leti=0;leta=()=>i++;letmem_a=mem(a);mem_a();console.log(i);//1mem_a();console.log(i);//1mem_a(10);console.log(i);//2mem_a();console.log(i);//2mem_a(11);console.log(i);//3letb=async()=>j++;letmem_b=mem(b);(async()=>{awaitmem_b();console.log(j);//1awaitmem_b();console.log(j);//1awaitmem_b(10);console.log(j);//2})();第二个参数用法用法:mem(Function,options|object)maxAge:设置缓存时长,默认infinityconstmem=require('mem');constgot=require('got');constdelay=require('延迟');constmemGot=mem(got,{maxAge:1000});(async()=>{awaitmemGot('sindresorhus.com');//这个调用被缓存awaitmemGot('sindresorhus.com');awaitdelay(2000);//这个调用没有被缓存,因为缓存有expiredawaitmemGot('sindresorhus.com');})();cacheKey:默认情况下,所有参数都一样开启缓存数据,也可以只设置第一个参数缓存(即只要第一个参数相同,就使用缓存的值)letc=(a,b)=>k++;letmem_c=mem(c);mem_c(1,2);console.log(k);//1mem_c(1,3);console.log(k);//2mem_c(1,3);console.log(k);//2letd=(a,b)=>l++;letmem_d=mem(d,{cacheKey:x=>JSON.stringify(x)});mem_d(1,2);console.log(l);//1mem_d(1,3);console.log(l);//1mem_d(2,3);console.log(l);//2cache:设置缓存方式,默认newMap(),如.has(key),.get(key),.set(key,value),.delete(key),可选。清除()。例如,您可以使用Wea??kMap代替或quick-lru用于LRUcache.cachePromiseRejection:拒绝缓存承诺的返回,默认为falsemem.clear(fn):清除函数的缓存数据