UNPKG

@knighttower/utility

Version:

UtilityJs is a utility library that provides a collection of utility functions for various tasks. The library is designed to be easy to use and covers the most common use cases.

1 lines 7.87 kB
var e,t;e=this,t=()=>(()=>{"use strict";var e={d:(t,s)=>{for(var r in s){e.o(s,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:s[r]})}},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{doAsync:()=>d,doPoll:()=>a,doTimeout:()=>h,promisePool:()=>c,promiseQueue:()=>l});class s{constructor(){this.listeners={}}on(e,t){this.registerListener(e,t)}once(e,t){this.registerListener(e,t,1)}exactly(e,t,s){this.registerListener(e,t,s)}off(e){delete this.listeners[e]}detach(e,t){const s=(this.listeners[e]||[]).filter(function(e){return e.callback!==t});return e in this.listeners&&(this.listeners[e]=s,!0)}emit(e,...t){let s=[],r=null;const i=this.extractContextFromArgs(t),n=i[0];if(t=i[1],this.hasListener(e)){s=this.listeners[e]}else if(e.includes("*")){r=this.patternSearch(e,Object.keys(this.listeners)),r.length>0&&r.forEach(e=>{s=s.concat(this.listeners[e])})}else{for(const t in this.listeners){t.includes("*")&&(r=this.patternSearch(t,[e]),r&&(s=s.concat(this.listeners[t])))}}s.forEach((r,i)=>{let o=r.callback;n&&(o=o.bind(n)),void 0!==r.triggerCapacity&&(r.triggerCapacity--,s[i].triggerCapacity=r.triggerCapacity),this.checkToRemoveListener(r)&&this.listeners[e].splice(i,1),o(...t)})}patternSearch(e,t){let s=[];const r=new RegExp(this.setWildCardString(e),"g");return s=t.filter(e=>r.test(e)),0===s.length?null:s}setWildCardString(e){let t=e.replace(/([.+?^${}()|\[\]\/\\])/g,"\\$&");return t=t.replace(/\*/g,"(.*?)"),`^${t}`}extractContextFromArgs(e){let t=null;for(let s=0;s<e.length;s++){const r=e[s];if(r&&"object"==typeof r&&r.hasOwnProperty("__context")){t=r.__context,e.splice(s,1);break}}return[t,e]}registerListener(e,t,s){this.hasListener(e)||(this.listeners[e]=[]),this.listeners[e].push({callback:t,triggerCapacity:s})}checkToRemoveListener(e){return void 0!==e.triggerCapacity&&e.triggerCapacity<=0}hasListener(e){return e in this.listeners}}const r=e=>Array.isArray(e)?e:[e],i=(e=20)=>{const t=()=>Math.random().toString(36).substring(2,15);e=e||40;for(var s="",r=0;r<e/3+1;r++){s+=t()}return s.substring(0,e)};function n(){return"id__"+i(8)+"__"+(new Date).getTime()}function o(e,t){if(null===e){return t?null===t||"null"===t:"null"}let s;switch(typeof e){case"number":case"string":case"boolean":case"undefined":case"bigint":case"symbol":case"function":s=typeof e;break;case"object":s=Array.isArray(e)?"array":"object";break;default:s="unknown"}if(t){if(t.includes("|")){for(let e of t.split("|")){if(s===e){return e}}return!1}return t===s}return s}const l=()=>{const e={completed:0,rejected:0,pending:0,total:0,errors:"",promises:[]};return new class extends s{constructor(){super(),this.queue=[],this.inProgress=!1,this._timer=null,this._stats={...e}}add(e){if(!(e instanceof Promise||Array.isArray(e)&&e.length>0&&e.every(e=>e instanceof Promise))){if(!o(e,"function")){return console.error("---\x3e Invalid promise added to the Queue:",e.toString()),this.emit("fail",e.toString())}e=new Promise(async t=>t(await e()))}r(e).forEach(e=>{this._stats.total++,this._stats.pending++,this.queue.push({promiseFunction:e,response:null,status:"pending",error:null})}),this.inProgress||this._next(),this._setTimer()}clear(){return this._timer&&clearInterval(this._timer),this._timer=null,this.queue=[],this.inProgress=!1,this._stats={...e},this}_setTimer(){this._timer&&clearInterval(this._timer),this._timer=setInterval(()=>{"done"===this.status()&&(clearInterval(this._timer),this._timer=null,this.emit("completed",this._stats),this.emit("done",this._stats))},10)}_next(){if(0===this.queue.length){return void(this.inProgress=!1)}this.inProgress=!0;const{promiseFunction:e}=this.queue[0];e.then(e=>{this.queue[0].status="fulfilled",this.queue[0].response=e,this._stats.completed++}).catch(e=>{this._stats.errors+=e+"\n",this.queue[0].status="rejected",this._stats.rejected++}).finally(()=>{this._stats.promises.push(this.queue[0]),this._stats.pending--,this.queue.shift(),this._next()})}stats(){return this._stats}status(){return 0===this.queue.length?"done":"in-progress"}}},a=(e,t={})=>{const s=e=>null!=e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then;if("function"!=typeof e&&!s(e)){throw new Error("doPoll: The first argument must be a function or Promise.")}const{msg:r,interval:i=200,timeout:n=1e3,timeoutMsg:l=r??null,signal:a}=t,c=Number.isFinite(i)&&i>0?i:200,u=Number.isFinite(n)&&n>0?n:1e3,h=s(e);let d,p,f,m,g=!1,_=!1,y=!1;const b=()=>{g=!0,d&&clearTimeout(d),p&&clearInterval(p),a&&a.removeEventListener?.("abort",x)},v=e=>{y||(y=!0,b(),f(e))},j=e=>{y||(y=!0,b(),m(e))},P=e=>"__TIMEOUT__"===e&&o(l,"string")?(console.info(l),j(l)):j(e),S=e=>{(o(e,"boolean")||e)&&v(e)},x=()=>P(a?.reason??"aborted");return{promise:new Promise((t,r)=>{f=t,m=r;const i=()=>{if(!(g||_||y)){try{const t=h?e:e(v,P);s(t)?(_=!0,t.then(e=>{_=!1,S(e)}).catch(e=>{_=!1,g||P(e)})):S(t)}catch(e){g||P(e)}}};h||(p=setInterval(i,c)),i(),d=setTimeout(()=>{g||P("__TIMEOUT__")},u),a?.aborted?x():a&&a.addEventListener?.("abort",x,{once:!0})}),stop:P}},c=()=>{let e="not-started";const t={},i=[];let o={completed:0,rejected:0,pending:0,total:0,errors:""};return new class extends s{constructor(){super();const e=this;this._currentPoll=null,setTimeout(()=>{e._poll()},100)}_poll(){const e=this;return this._currentPoll&&this._currentPoll.stop(),this._currentPoll=a(()=>{if(e.isDone()){return!0}},{timeoutMsg:""}),this._currentPoll}clear(){e="not-started",o={completed:0,rejected:0,pending:0,total:0,errors:""},i.length=0,Object.keys(t).forEach(e=>{t[e].rejecter("Promise pool cleared."),delete t[e]}),this._currentPoll=this._poll()}add(s){const l=this;s?(e="in-progress",r(s).forEach(e=>{if(!(e instanceof Promise)){if("function"!=typeof e){return console.info("---\x3e Invalid promise added to the pool."),void i.push(e.toString())}e=d(()=>e())}o.total++;const s=n();t[s]={status:"in-progress",response:null,error:null,resolver:null,rejecter:null},new Promise((r,n)=>{t[s].resolver=e=>{"rejected"!==t[s].status&&(t[s].status="completed",t[s].response=e,l._updateStatus(),r(e))},t[s].rejecter=e=>{t[s].status="rejected",t[s].error=e,i.push(e),l._updateStatus(),n()},e.then(e=>{t[s]?.resolver(e)}).catch(e=>{t[s]?.rejecter(e)})}).catch(e=>{t[s]?.rejecter(e)})})):l._updateStatus()}status(){return this._updateStatus(),e}isDone(){return this._updateStatus(),"done"===e}isEmpty(){return 0===o.total}results(){return this._updateStatus(),o}stats(){return this.results()}_updateStatus(){if("done"===e){return}const s=Object.values(t);o={completed:s.filter(e=>"completed"===e.status).length,rejected:s.filter(e=>"rejected"===e.status).length,pending:s.filter(e=>"in-progress"===e.status).length,total:s.length,errors:i.join("\n"),promises:t},this.emit("stats",o);const r=s.every(e=>"completed"===e.status||"rejected"===e.status);e=r||0===o.total?"done":"in-progress","done"===e&&(this.emit("done",o),o.total>0&&(this.emit("completed",o),this.emit("rejected",i,o)))}}},u={};function h(e,t,s,...r){let i,n;if("string"==typeof e&&"number"==typeof t){i=e,n=t}else if("number"==typeof e&&"function"==typeof t){n=e,s=t}else{if(t||"string"!=typeof e){throw new Error("Invalid parameters")}i=e}const o=i?"_doTimeout_"+i:null;function l(){o&&o in u&&delete u[o]}if(o&&o in u&&(clearTimeout(u[o]),delete u[o]),"function"==typeof s&&"number"==typeof n){return function e(){u[o]=setTimeout(()=>{!0===s(...r)?e():l()},n)}(),!0}i&&void 0===n&&l()}function d(e,...t){return new Promise((s,r)=>{try{Promise.resolve(e(...t)).then(e=>s(e)).catch(e=>r(e))}catch(e){r(e)}})}return t})(),"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("promises",[],t):"object"==typeof exports?exports.promises=t():e.promises=t();