Priority Queue Practice

by Steven Senkus

JavaScript

function Queue() {
    this.dataStore = [];
}

Queue.prototype.enqueue = function (element) {
    this.dataStore.push(element);
};
/*
Queue.prototype.dequeue = function () {
    return this.dataStore.shift();
};
*/
Queue.prototype.dequeue = function () {
    var priority = this.dataStore[0].code;
    for (var i = 1; i < this.dataStore.length; ++i) {
        if (this.dataStore[i].code < priority) {
            priority = i;
        }
    }
    return this.dataStore.splice(priority, 1);
};


Queue.prototype.front = function () {
    return this.dataStore[0];
};
Queue.prototype.back = function () {
    return this.dataStore[this.dataStore.length - 1]
};
Queue.prototype.toString = function () {
    var returnString = '';
    for (var i = 0; i < this.dataStore.length; ++i) {
        returnString += ('NAME: ' + this.dataStore[i].name + ' CODE: ' + this.dataStore[i].code + "\n");
    
    }
    return returnString;
};
Queue.prototype.empty = function () {
    return this.dataStore.length === 0;
};

function Patient(name, code) {
    this.name = name;
    this.code = code;
}


var p = new Patient("Smith", 5);
var ed = new Queue();
ed.enqueue(p);
p = new Patient("Jones", 4);
ed.enqueue(p);
p = new Patient("Fehrenbach", 6);
ed.enqueue(p);
p = new Patient("Brown", 1);
ed.enqueue(p);
p = new Patient("Ingram", 1);
ed.enqueue(p);
console.log(ed.toString());
var seen = ed.dequeue();
console.log("Patient being treated: " + seen[0].name);
console.log("Patients waiting to be seen: ")
console.log(ed.toString());
// another round
var seen = ed.dequeue();
console.log("Patient being treated: " + seen[0].name);
console.log("Patients waiting to be seen: ")
console.log(ed.toString());
var seen = ed.dequeue();
console.log("Patient being treated: " + seen[0].name);