pathterminuspages/snippets/aboutcontactabout me

Implementing a queue in JavaScript

18.12.2017

OK. Lets implement a queue in JavaScript. This is quite easy when exploiting that JS has first class functions with closures. Lets just jump right into it:

var Queue = function(){ var head = null; var tail = null; var pub = {}; pub.length = 0; pub.peek = function(){ if(head !== null){ return head.val; } return null; }; pub.push = function(val){ var node = {}; node.next = null; node.val = val; this.length++; if(head === null){ head = node; tail = node; } else { tail.next = node; tail = node; } }; pub.pop = function(){ var retval = head; if(retval === null){ return retval; } this.length--; head = head.next; return retval.val; }; pub.fold = function(f,acc){ while(head !== null){ acc = f(head.val,acc); head = head.next; } this.length = 0; return acc; }; pub.foreach = function(f){ var node0 = head; while(node0 !== null){ f(node0.val); node0 = node0.next; } }; return pub; };

fold actually disassamble the whole queue for the garbage collector to take care of. foreach on the other hand just, yeah, does what foreach does. Cool. So init and test:

var q1 = new Queue(); q1.push("one"); q1.push("two"); q1.push("three"); q1.push("four");

Test 1:

q1.foreach(function(elm){ console.log(elm); });

Test 2:

console.log(q1.pop()); console.log(q1.pop()); console.log(q1.pop()); console.log(q1.pop()); console.log(q1.pop()); console.log(q1.pop());

The last two prints null as supposed to.

Test 3 (first refill the queue):

var qstr1 = q1.fold(function(elm,acc){ return acc + elm + "<br>"; },""); console.log(qstr1);

And so on...

CommentsGuest Name:Comment: