Parallel

try to take over the world!

Tính đến 18-03-2019. Xem phiên bản mới nhất.

Script này sẽ không được không được cài đặt trực tiếp. Nó là một thư viện cho các script khác để bao gồm các chỉ thị meta // @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;
    }
}