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.95 kB
var e,t;e=this,t=()=>(()=>{"use strict";var e={d:(t,r)=>{for(var s in r){e.o(r,s)&&!e.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:r[s]})}},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 r{constructor(){this.listeners={}}on(e,t){this.registerListener(e,t)}once(e,t){this.registerListener(e,t,1)}exactly(e,t,r){this.registerListener(e,t,r)}off(e){delete this.listeners[e]}detach(e,t){const r=(this.listeners[e]||[]).filter((function(e){return e.callback!==t}));return e in this.listeners&&(this.listeners[e]=r,!0)}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),s=1;s<t;s++){r[s-1]=arguments[s]}let i=[],n=null;const o=this.extractContextFromArgs(r),l=o[0];if(r=o[1],this.hasListener(e)){i=this.listeners[e]}else if(e.includes("*")){n=this.patternSearch(e,Object.keys(this.listeners)),n.length>0&&n.forEach((e=>{i=i.concat(this.listeners[e])}))}else{for(const t in this.listeners){t.includes("*")&&(n=this.patternSearch(t,[e]),n&&(i=i.concat(this.listeners[t])))}}i.forEach(((t,s)=>{let n=t.callback;l&&(n=n.bind(l)),void 0!==t.triggerCapacity&&(t.triggerCapacity--,i[s].triggerCapacity=t.triggerCapacity),this.checkToRemoveListener(t)&&this.listeners[e].splice(s,1),n(...r)}))}patternSearch(e,t){let r=[];const s=new RegExp(this.setWildCardString(e),"g");return r=t.filter((e=>s.test(e))),0===r.length?null:r}setWildCardString(e){let t=e.replace(/([.+?^${}()|\[\]\/\\])/g,"\\$&");return t=t.replace(/\*/g,"(.*?)"),`^${t}`}extractContextFromArgs(e){let t=null;for(let r=0;r<e.length;r++){const s=e[r];if(s&&"object"==typeof s&&s.hasOwnProperty("__context")){t=s.__context,e.splice(r,1);break}}return[t,e]}registerListener(e,t,r){this.hasListener(e)||(this.listeners[e]=[]),this.listeners[e].push({callback:t,triggerCapacity:r})}checkToRemoveListener(e){return void 0!==e.triggerCapacity&&e.triggerCapacity<=0}hasListener(e){return e in this.listeners}}const s=e=>Array.isArray(e)?e:[e],i=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:20;e=e||40;for(var t="",r=0;r<e/3+1;r++){t+=Math.random().toString(36).substring(2,15)}return t.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 r;switch(typeof e){case"number":case"string":case"boolean":case"undefined":case"bigint":case"symbol":case"function":r=typeof e;break;case"object":r=Array.isArray(e)?"array":"object";break;default:r="unknown"}if(t){if(t.includes("|")){for(let e of t.split("|")){if(r===e){return e}}return!1}return t===r}return r}const l=()=>{const e={completed:0,rejected:0,pending:0,total:0,errors:"",promises:[]};return new class extends r{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())))}s(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=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("function"!=typeof e&&"object"!=typeof e){throw new Error("doPoll: The first argument must be a function or Promise.")}const r=e=>e instanceof Promise,{msg:s,interval:i=200,timeout:n=1e3,timeoutMsg:l=s??null}=t;let a,c,u,h,d=!1,p=!1;const f=()=>{if(g(),o(l,"string")){return console.info(l),void h(l)}h()},m=e=>{g(),u(e)};function g(){d=!0,clearTimeout(a),clearInterval(c)}const y=new Promise(((t,s)=>{u=t,h=s;const o=()=>{if(d||p){return}const t=r(e)?e:e();r(t)?(p=!0,t.then((e=>{p=!1,e&&m(e)})).catch(h)):(Boolean(t)||t)&&m(t)};c=setInterval(o,i),o(),a=setTimeout((()=>{d||f()}),n)}));return y.catch((()=>{f()})),{promise:y,stop:f}},c=()=>{let e="not-started";const t={},i=[];let o={completed:0,rejected:0,pending:0,total:0,errors:""};return new class extends r{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(r){const l=this;r?(e="in-progress",s(r).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 r=n();t[r]={status:"in-progress",response:null,error:null,resolver:null,rejecter:null},new Promise(((s,n)=>{t[r].resolver=e=>{"rejected"!==t[r].status&&(t[r].status="completed",t[r].response=e,l._updateStatus(),s(e))},t[r].rejecter=e=>{t[r].status="rejected",t[r].error=e,i.push(e),l._updateStatus(),n()},e.then((e=>{t[r]?.resolver(e)})).catch((e=>{t[r]?.rejecter(e)}))})).catch((e=>{t[r]?.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 r=Object.values(t);o={completed:r.filter((e=>"completed"===e.status)).length,rejected:r.filter((e=>"rejected"===e.status)).length,pending:r.filter((e=>"in-progress"===e.status)).length,total:r.length,errors:i.join("\n"),promises:t},this.emit("stats",o);const s=r.every((e=>"completed"===e.status||"rejected"===e.status));e=s||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,r){for(var s=arguments.length,i=new Array(s>3?s-3:0),n=3;n<s;n++){i[n-3]=arguments[n]}let o,l;if("string"==typeof e&&"number"==typeof t){o=e,l=t}else if("number"==typeof e&&"function"==typeof t){l=e,r=t}else{if(t||"string"!=typeof e){throw new Error("Invalid parameters")}o=e}const a=o?"_doTimeout_"+o:null;function c(){a&&a in u&&delete u[a]}if(a&&a in u&&(clearTimeout(u[a]),delete u[a]),"function"==typeof r&&"number"==typeof l){return function e(){u[a]=setTimeout((()=>{!0===r(...i)?e():c()}),l)}(),!0}o&&void 0===l&&c()}function d(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),s=1;s<t;s++){r[s-1]=arguments[s]}return new Promise(((t,s)=>{try{Promise.resolve(e(...r)).then((e=>t(e))).catch((e=>s(e)))}catch(e){s(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();