@utilify/function
Version:
These utilities help with tasks such as debouncing, throttling, function composition, and managing async behavior, making it easier to handle function flow and optimize performance.
2 lines (1 loc) • 1.76 kB
JavaScript
;exports.benchmark=function(t,e=1){return new Promise((async r=>{const n=[];for(let r=0;r<e;r++){const e=performance.now();await t();const r=performance.now();n.push(r-e)}r(function(t){return t.length?function(t){return t.reduce(((t,e)=>t+e),0)}(t)/t.length:0}(n))}))},exports.compose=function(...t){return e=>t.reduceRight(((t,e)=>e(t)),e)},exports.debounce=function(t,e=300){let r;return(...n)=>{clearTimeout(r),r=setTimeout((()=>t(...n)),e)}},exports.defer=function(t){Promise.resolve().then(t)},exports.fallback=function(t,e){try{return t()}catch{return e()}},exports.guard=function(t,e,r){return(...n)=>t(...n)?e(...n):r(...n)},exports.identity=function(t){return t},exports.lock=function(t){let e=!1;return async(...r)=>{if(!e){e=!0;try{await t(...r)}catch(t){console.error("Callback execution error:",t)}finally{e=!1}}}},exports.memo=function(t,e){const r=new Map;return(...n)=>{const o=function(t){let e=5381;for(let r=0;r<t.length;r++)e=33*e^t.charCodeAt(r);return String(e>>>0)}(JSON.stringify(n));return r.has(o)||(r.set(o,t(...n)),e&&setTimeout((()=>r.delete(o)),e)),r.get(o)}},exports.noop=function(){},exports.once=function(t){let e,r=!1;return(...n)=>(r||(r=!0,e=t(...n)),e)},exports.parallel=async function(...t){return Promise.all(t.map((t=>t())))},exports.partialLeft=function(t,...e){return(...r)=>t(...e,...r)},exports.partialRight=function(t,...e){return(...r)=>t(...r,...e)},exports.pipe=function(...t){return e=>t.reduce(((t,e)=>e(t)),e)},exports.rate=function(t,e,r){let n=0;return(...o)=>n<e&&(0===n&&setTimeout((()=>{n=0}),r),n++,t(...o),!0)},exports.sleep=async function(t){return new Promise((e=>setTimeout(e,t)))},exports.throttle=function(t,e=300){let r;return(...n)=>{r||(r=setTimeout((()=>r=null),e),t(...n))}};