Skip to content

Instantly share code, notes, and snippets.

@jayde-bog
Last active June 27, 2019 02:01
Show Gist options
  • Save jayde-bog/a9214f5178a3ce0deb3981e8b7e0ab69 to your computer and use it in GitHub Desktop.
Save jayde-bog/a9214f5178a3ce0deb3981e8b7e0ab69 to your computer and use it in GitHub Desktop.
javascript: Queue
import EventEmitter from 'events';
class Node {
constructor(data) {
this._data = data;
this._next = null;
}
get data() {
return this._data;
}
get next() {
return this._next;
}
set next(val) {
this._next = val;
}
}
class Queue extends EventEmitter {
constructor(initDatas = [], maxSize = 0) {
super();
EventEmitter.call(this);
this._front = null;
this._tail = null;
this._size = 0;
this._maxSize = maxSize;
for (const d of initDatas) {
this.enque(d);
}
}
push(data) {
const node = new Node(data);
if (!this._tail) {
this._front = node;
this._tail = node;
} else {
this._tail.next = node;
this._tail = node;
}
this._size += 1;
if (this._maxSize > 0 && this._size > this._maxSize) {
this.pop();
}
this.emit('pushed');
return this._size;
}
pop() {
if (!this._front || this._size === 0) return null;
const node = this._front;
this._front = this._front.next;
if (!this._front) {
this._tail = null;
}
this._size = Math.max(0, this._size - 1);
return node.data;
}
clear() {
while (this.size() > 0) {
this.pop();
}
}
size() {
return Math.max(0, this._size);
}
}
export default Queue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment