Parallel

try to take over the world!

Version vom 18.03.2019. Aktuellste Version

Dieses Skript sollte nicht direkt installiert werden. Es handelt sich hier um eine Bibliothek für andere Skripte, welche über folgenden Befehl in den Metadaten eines Skriptes eingebunden wird // @require https://update.greasyfork.org/scripts/380535/680851/Parallel.js

// ==UserScript==
// @name         Parallel
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// ==/UserScript==

class Parallel{
    constructor(count=3){
        this.count=3
    }

    partial(data,count){
        let r=[];
        let l=data.length;
        let dataPerThread=parseInt(l/count);
        if (dataPerThread==0){
            dataPerThread=1;
        }
        for (let i=0;i<l;i+=dataPerThread){
            let to=Math.min(i+dataPerThread,l);
            let d=data.slice(i,to);
            r.push(d);
        }
        return r;
    }

    async run(data,action,isReturn=false){
        let results=[];
        for (let x in data){
			let r=action(data[x]);
			if (r instanceof Promise){
				r=await r;
			}
            if (isReturn){
                results.push(r);
            }
        }
        if (isReturn){
            return results;
        }
    }

    async forEach(data,action){
        data=this.partial(data,this.count);
        let threads=[];
        for (let i in data){
            let d=data[i];
            threads.unshift(this.run(d,action));
        }
        for (let x in threads){
            await threads[x];
        }
    }

    async map(data,action){
        data=this.partial(data,this.count);
        let threads=[];
        for (let i in data){
            let d=data[i];
            threads.unshift(this.run(d,action,true));
        }
        let results=[];
        for (let x in threads){
            results=results.concat(await threads[x]);
        }
        return results;
    }
}