mimicry/queue.js

77 lines
2.2 KiB
JavaScript

"use strict";
(function queuePrivateClosure () {
/**
* This class is a primitive doubly linked list, I need it to implement a queue
* */
class Queue {
constructor () {
this._head = new Node(null);
this._tail = this._head;
this._head.next = this._tail;
this._head.prev = this._tail;
this.length = 0;
}
/**
* Check if the queue is empty
*
* @returns Boolean
* */
get empty () {return this._head === this._tail;}
/**
* Adds element to the end of the queue.
* Data is not copied, now ownership taken
*
* @param {any} data - a data you wish to add
* */
push (data) {
const node = new Node(data);
node.prev = this._head.prev;
node.next = this._head;
this._head.prev = node;
this._head = node;
++this.length;
}
/**
* Removes element from the beginning of the queue and returns it
*
* @returns {any} - a data from the list
* @throws Error if the list was empty
* */
pop () {
if (this.empty)
throw new Error("An attempt to pop from an empty queue");
const node = this._tail.prev;
const data = node.data;
node.prev.next = node.next;
node.next.prev = node.prev;
if (this._head === node) {
this._head = node.next;
}
--this.length;
return data;
}
}
/**
* A helper class for the Queue, just a data structure with getters
* */
class Node {
constructor (data) {
this._data = data;
this._next = null; //Node
this._prev = null; //Node
}
get data () {return this._data;}
get next () {return this._next;}
set next (/*Node*/node) {this._next = node;}
get prev () {return this._prev;}
set prev (/*Node*/node) {this._prev = node;}
}
if (typeof module === 'object' && module.exports)
module.exports = Queue;
else
window.__MimicryQueue__ = Queue;
})();