Created
October 17, 2016 10:56
-
-
Save tcstory/d38a60b52e39c619130391cac0bab631 to your computer and use it in GitHub Desktop.
This file contains 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
class Queue { | |
constructor() { | |
this._items = []; | |
} | |
enqueue(element) { | |
if (Array.isArray(element)) { | |
this._items.push(...element); | |
} else { | |
this._items.push(element); | |
} | |
} | |
dequeue() { | |
return this._items.shift(); | |
} | |
front() { | |
return this._items[0]; | |
} | |
isEmpty() { | |
return this._items.length === 0; | |
} | |
get size() { | |
return this._items.length; | |
} | |
clear() { | |
return this._items = []; | |
} | |
print() { | |
console.log(this._items.toString()); | |
} | |
} | |
class PriorityQueue extends Queue { | |
enqueue(element, priority) { | |
if (this.isEmpty()) { | |
this._items.push({ | |
element, | |
priority, | |
}); | |
} else { | |
let added = false; | |
for (let i = 0, len = this._items.length; i < len; i++) { | |
if (this._items[i].priority > priority) { | |
this._items.splice(i,0, { | |
element, | |
priority, | |
}); | |
added = true; | |
break; | |
} | |
} | |
if (!added) { | |
this._items.push({ | |
element, | |
priority, | |
}); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment