Skip to content

Latest commit

 

History

History
111 lines (87 loc) · 2.1 KB

README.md

File metadata and controls

111 lines (87 loc) · 2.1 KB

js-simple-queue

The simplest queue in JavaScript, only few lines.

queue without size support

function SimpleQueue(){

}

SimpleQueue.prototype.push=function(e){
    this.tail=this.head?this.tail[1]=[e,null]:this.head=[e,null];
}

SimpleQueue.prototype.shift=function(){
    return this.head?[this.head[0],this.head=this.head[1]][0]:null;
}

SimpleQueue.prototype.clear=function(){
    this.head=this.tail=null;
}

SimpleQueue.prototype.isEmpty=function(){
    return !this.head;
}
//if you want to use it as nodejs module, uncomment it
//module.exports=SimpleQueue;

queue with size support

function SimpleQueue(){
    this.length=0;
}

SimpleQueue.prototype.push=function(e){
    this.tail=this.length++?this.tail[1]=[e,null]:this.head=[e,null];
}

SimpleQueue.prototype.shift=function(){
    return this.length?[this.head[0],this.head=this.head[1],this.length--][0]:null;
}

SimpleQueue.prototype.clear=function(){
    this.head=this.tail=null;
    this.length=0;
}

SimpleQueue.prototype.isEmpty=function(){
    return this.length==0;
}

SimpleQueue.prototype.size=function(){
    return this.length;
}
//if you want to use it as nodejs module, uncomment it
//module.exports=SimpleQueue;

create queue

//const SimpleQueue = require('./SimpleQueue');;
var queue=new SimpleQueue();

is empty

console.log(queue.isEmpty()?"notEmpty":"empty");

push/add/enqueue

for(i=0;i<5;i++){
    queue.push(i);
}

shift/poll/dequeue

for(;!queue.isEmpty();){
    console.log(queue.shift());
}

clear

queue.clear();

benchmark

for(i=0;i<1024*1024;i++){
    queue.push(i);
}

var st=new Date().getTime();
for(i=0;i<1024*1024;i++){
    queue.push(i);
    queue.shift();
}
console.log("cost "+(new Date().getTime()-st)+" ms for "+1024*1024+" ops");
//cost 39 ms for 1048576 ops

Projects

js-simple-queue some nodejs module need a queue, so i write one

Support

glad to see you, if you need some support, contact QIAN YU or post in issues.