Last active
June 27, 2019 02:01
-
-
Save jayde-bog/a9214f5178a3ce0deb3981e8b7e0ab69 to your computer and use it in GitHub Desktop.
javascript: Queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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