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