add a simpler solution to Priority Queue
Existing solution is a bit overkill (reduce + temp array). This PR introduces, I believe, a simpler to understand solution.
This commit is contained in:
@ -187,7 +187,7 @@
|
||||
"type": "waypoint",
|
||||
"releasedOn": "Feb 17, 2017",
|
||||
"solutions": [
|
||||
"function PriorityQueue () { \n this.collection = []; \n this.printCollection = function(){ \n console.log(this.collection); \n }; \n this.size = function() { \n return this.collection.length; \n }; \n this.isEmpty = function() { \n return this.size() > 0 ? false : true; \n }; \n this.enqueue = function(newItem) { \n if (this.isEmpty()) { \n this.collection.push(newItem) \n } else { \n let inserted = false; \n var updated = this.collection.reduce((newCollection, item, index, current) => { \n if (newItem[1] < item[1] && !inserted) { \n newCollection.push(newItem); \n inserted = true; \n } \n newCollection.push(item); \n if (newItem[1] === item[1] && index < current.length - 1 && newItem[1] !== current[index + 1][1] && !inserted) { \n newCollection.push(newItem); \n inserted = true; \n } \n return newCollection; \n }, []); \n if (!inserted) { \n updated.push(newItem); \n } \n this.collection = updated; \n }; \n }; \n this.dequeue = function() { \n if (!this.isEmpty()) { \n return this.collection.shift()[0]; \n } else { \n return 'The queue is empty.' \n } \n }; \n }"
|
||||
"function PriorityQueue () { \n this.collection = []; \n this.printCollection = function(){ \n console.log(this.collection); \n }; \n this.size = function() { \n return this.collection.length; \n }; \n this.isEmpty = function() { \n return this.size() > 0 ? false : true; \n }; \n this.enqueue = function (newitem) {\n if (this.isEmpty()) {\n return this.collection.push(newitem);\n }\n\n this.collection = this.collection.reverse();\n var found_index = this.collection.findIndex(function (item) {\n return newitem[1] >= item[1];\n });\n if (found_index === -1) {\n this.collection.push(newitem);\n } else {\n this.collection.splice(found_index, 0, newitem);\n }\n this.collection = this.collection.reverse();\n}; \n this.dequeue = function() { \n if (!this.isEmpty()) { \n return this.collection.shift()[0]; \n } else { \n return 'The queue is empty.' \n } \n }; \n }"
|
||||
],
|
||||
"challengeType": 1,
|
||||
"translations": {}
|
||||
|
Reference in New Issue
Block a user