Skip to content
fifo.js 1.56 KiB
Newer Older
var fifo = function () {
    /**
     * an unbounded fifo queue.
     */
    const Queue = function () {
	this.data = [];
	this.push = function (e) {
	    this.data.push(e);
	};
	/**
	 * note: pop() will return undefined when there is not enough element.
	 */
	this.pop = function () {
	    return this.data.shift();
	};
    };

    /**
     * a bounded fifo queue.
     */
    const BoundedQueue = function (capacity) {
	this.capacity = capacity;
	this.data = [];
	/**
	 * push new element to the BoundedQueue. if there is no room for it,
	 * remove the oldest element from the queue.
	 */
	this.push = function (e) {
	    console.assert(this.data.length <= this.capacity, "bounded queue data size is invalid");
	    if (this.data.length === this.capacity) {
		this.data.shift();
	    }
	    this.data.push(e);
	};
	/**
	 * note: pop() will return undefined when there is not enough element.
	 */
	this.pop = function () {
	    return this.data.shift();
	};
    };

    const testFIFO = function () {
	var q = new Queue();
	q.push(1);
	q.push(2);
	q.push(3);
	console.assert(q.pop() === 1);
	console.assert(q.pop() === 2);
	console.assert(q.pop() === 3);

	q = new BoundedQueue(3);
	q.push(1);
	q.push(2);
	q.push(3);
	console.assert(q.pop() === 1);
	console.assert(q.pop() === 2);
	console.assert(q.pop() === 3);

	q = new BoundedQueue(3);
	q.push(1);
	q.push(2);
	q.push(3);
	q.push(4);
	console.assert(q.pop() === 2);
	console.assert(q.pop() === 3);
	console.assert(q.pop() === 4);
    };

    // run all tests
    testFIFO();

    return {
	Queue: Queue,
	BoundedQueue: BoundedQueue,
    };
}();