Last active
August 26, 2019 10:02
-
-
Save giscafer/e951ac74d27bacd3deb2edce44c082e0 to your computer and use it in GitHub Desktop.
JavaScript类模拟队列实现
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
/** | |
* @author: giscafer ,https://github.com/giscafer | |
* @date: 2018-07-25 15:59:02 | |
* @description: 类实现队列模拟 | |
*/ | |
const Queue = (() => { | |
// 闭包实现私有变量 | |
let item = new WeakMap(); | |
class Queue { | |
get q() { | |
return item.get(this); | |
} | |
constructor() { | |
item.set(this, []); | |
} | |
enqueue(element) { | |
this.q.push(element); | |
} | |
dequeue() { | |
return this.q.shift(); | |
} | |
front() { | |
return this.q[0]; | |
} | |
isEmpty() { | |
return this.q.length === 0; | |
} | |
size() { | |
return this.q.length; | |
} | |
print() { | |
return this.q.toString(); | |
} | |
} | |
return Queue; | |
})(); | |
/* 优先队列 */ | |
class QueueElement { | |
constructor(element, priority) { | |
this.element = element; | |
this.priority = priority; | |
} | |
} | |
// 优先队列,根据优先级确定任务所在队列位置 | |
class PriorityQueue { | |
constructor() { | |
this.items = []; | |
} | |
enqueue(element, priority) { | |
let qElement = new QueueElement(element, priority); | |
let added = false; | |
for (let i = 0; i < this.items.length; i++) { | |
if (qElement.priority < this.items[i].priority) { | |
this.items.splice(i, 0, qElement); | |
added = true; | |
break; | |
} | |
} | |
if (!added) { | |
this.items.push(qElement); | |
} | |
} | |
print() { | |
for (let i = 0; i < this.items.length; i++) { | |
console.log(`${this.items[i].element} - ${this.items[i].priority}`); | |
} | |
} | |
} | |
// test | |
let priorityQueue = new PriorityQueue(); | |
priorityQueue.enqueue("John", 2); | |
priorityQueue.enqueue("Jack", 1); | |
priorityQueue.enqueue("Camila", 1); | |
priorityQueue.print(); | |
// 循环队列(击鼓传花) | |
function hotPotato(nameList, num) { | |
let queue = new Queue(); | |
for (let i = 0; i < nameList.length; i++) { | |
queue.enqueue(nameList[i]); | |
} | |
let eliminated = ''; | |
while (queue.size() > 1) { | |
for (let i = 0; i < num; i++) { | |
queue.enqueue(queue.dequeue()); | |
} | |
eliminated = queue.dequeue(); | |
console.log(eliminated + '在击鼓传花游戏中杯淘汰。'); | |
} | |
return queue.dequeue(); | |
} | |
let names = ['John', 'Jack', 'Camila', 'Ingrid', 'Carl']; | |
let winner = hotPotato(names, 7); | |
console.log('The winner is: ' + winner); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/loiane/javascript-datastructures-algorithms