forked from lukeschaefer/WorkerBee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sideworker.min.js
1 lines (1 loc) · 1.59 KB
/
sideworker.min.js
1
var SideWorker=function(){"use strict";const e=e=>{e&&console.debug("SideWorker initialised.");const t="ERROR! FUNCTION NOT DEFINED!",s=e=>e.split(":");const n=new function(){this.func=!1,this.define=(e,t)=>{const s=new Function("return "+t)();this[e]=(t,n)=>{self.postMessage(((...e)=>e.join(":"))(e,t));try{const e=s.apply(this,n);self.postMessage([,e])}catch(e){self.postMessage([e])}this.func=!1}}};self.addEventListener("message",(i=>{if(n.func){const c=n.func,[o,r]=s(c);if(n.func=!1,e&&("define"===o?console.debug(`Defining "${i.data[0]}"`):console.debug(`Calling "${o}" (id: ${r})`)),n[o]){const e="define"!==o||r?[r,i.data]:i.data;n[o].apply(n,e)}else console.error(t,n[o])}else{n.func=i.data;const[e]=s(i.data);n[e]||console.error(t,e)}}))};return function({debug:t,init:s}={},...n){const i=e.toString().replace(/^\(?([a-z]+)\)?\s*=>\s*{/,((e,s)=>`const ${s}=${t?1:0};`)).replace(/}$/,""),c=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));this.worker=new Worker(c),URL.revokeObjectURL(c),this.func=null,this._cb=new Map,this.run={},this.callFunction=(e,...t)=>{this.worker.postMessage(e),this.worker.postMessage(t)},this.define=(e,t)=>{this.callFunction("define",e,t.toString()),this.run[e]=(...t)=>new Promise(((s,n)=>{const i=`${e}:${URL.createObjectURL(new Blob).split("/").pop()}`;this._cb.set(i,{resolve:s,reject:n}),this.callFunction(i,...t)}))},this.worker.addEventListener("message",(e=>{if(this.func){const[t,...s]=e.data,n=this._cb.get(this.func);t?n.reject(t):n.resolve(...s),this._cb.delete(this.func),this.func=null}else this.func=e.data})),s&&(this.define("init",s),this.run.init(n))}}();