Skip to content

Instantly share code, notes, and snippets.

@dev-ashishk
Created August 20, 2019 16:53
Show Gist options
  • Save dev-ashishk/570049cac458fe7234e20ad691c7832e to your computer and use it in GitHub Desktop.
Save dev-ashishk/570049cac458fe7234e20ad691c7832e to your computer and use it in GitHub Desktop.
/**
* @author {Ashish Kumar}
* @param {function} cb
* @return {Class} MAX_COUNT
* ParallelQueue will execute 5 OR MAX_COUNT process in parallel.
* It will always make sure that the execution queue will always have 5 process to execute.
*/
class ParallelQueue {
constructor(cb,MAX_COUNT){
this.callback = cb || function(){};
this.__queue__ = [];
this.__execQueue__ = [];
this.MAX_COUNT = MAX_COUNT || 5;
}
/**
* @param {function} cb;
* to set new callback handler for the Queue
*/
setHandler = (cb) => {
this.callback = cb;
};
/**
* @param {function} fn;
* add function or process to queue
*/
add = (fn) => {
this.__queue__.push(fn);
this.next();
return this.__queue__;
};
/**
* To pull process from main queue,
*/
pull = () => {
const len = this.__queue__.length;
if(!len){
return {
error : true,
msg : "Empty Queue !"
};
}
const fn = this.__queue__[0];
this.__queue__ = this.__queue__.slice(1);
return {
error : false,
payload : fn,
msg : `payload from index-0`
};
};
/**
* This will be sent to the Queue handler as a callback function,
* This will also removed the executed process from the __execQueue__ (Execution Queue)
* @param {Boolean} bool
* @param {Number} index
*/
done = (bool,index) => {
if(bool,index){
this.__execQueue__ = this.__execQueue__.splice(index, 1);
}
}
/**
* next() is to execute the next process in the queue
*/
next = () => {
if(this.__execQueue__.length <= this.MAX_COUNT - 1){
const val = this.pull();
if(!val.error){
this.__execQueue__.push(val.payload);
this.callback(val.payload,this.__execQueue__.length - 1, this.done);
this.next();
}
}
}
}
function handle(val,index,done){
new Promise((res,rej) => {
setTimeout(() => {
console.log(`${val} -- ${index} --- ${Date.now()}`)
done(true,index);
},Math.floor((Math.random() * 2000) + 1));
})
}
const q = new ParallelQueue(handle);
q.add("a");
q.add("b");
q.add("c");
q.add("d");
q.add("e");
q.add("f");
q.add("g");
let i = 0;
const interval = setInterval(() => {
if(i >= 10){
clearInterval(interval);
}
q.add(i);
i++;
},100);
setTimeout(function(){
q.add("6576676");
},15000);
setTimeout(function(){
q.add("656---------------");
},5000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment