Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement