根據書上例子的實際要求,涉及到js隊列的問題。所以先把js中隊列的具體實現數據結構貼出來。具體參考《學習javascript數據結構和算法》第四章。
隊列數據結構遵循先入先出的原則。入隊操作添加到數組的末尾,返回新數組。出隊操作彈出數組第一個元素,返回新數組。兩個操作對于數組都有結構的改變
//js中隊列的實現是依賴數組的數據結構
function Queue() {
let items = []; //初始化空數組,let關鍵字是es6中的
//用于形成大括號包圍的作用域
this.enqueue = function(element){ //入隊操作
items.push(element); //數組push操作
};
this.dequeue = function(){//出對
return items.shift(); //數組shift操作
};
this.front = function(){ //隊列第一個元素
return items[0]; //數組第一個元素
};
this.isEmpty = function(){ //判斷隊列有無成員
return items.length == 0; //布爾值判斷
};
this.clear = function(){ //清空隊列
items = []; //變量重新賦值空數組
};
this.size = function(){ //獲得隊列的長度
return items.length;
};
this.print = function(){ //打印隊列
console.log(items.toString());
};
}
下面是優先隊列。數據成員入隊的時候要攜帶數據和優先級。
優先級在這里的定義是數字越大在數組中的位置靠后。當插入一個數組元素的時候,先要根據它的優先級來判斷,最小是直接插入到第一位,緊鄰一個比他大的優先級是,就插入到這個鄰居的前面。如果是最大的數字就插到數組的最后。
一維數組變成了二位數組。
function PriorityQueue() {
let items = [];
function QueueElement (element, priority){
this.element = element;//成員本身
this.priority = priority; //優先級
}
this.enqueue = function(element, priority){
let queueElement = new QueueElement(element, priority);
let added = false; //添加標記
for (let i=0; i<items.length; i++){
if (queueElement.priority <
items[i].priority){ //找到優先級數字比他大的那個元素
items.splice(i,0,queueElement);
// 插到這個元素的前面
added = true;
break; // 終止
}
}
if (!added){ //如果是優先級數字是最大的,直接插入到
//數組的末尾
items.push(queueElement); //{5}
}
};
//其他操作和普通隊列是一樣的
this.dequeue = function(){
return items.shift();
};
this.front = function(){
return items[0];
};
this.isEmpty = function(){
return items.length == 0;
};
this.size = function(){
return items.length;
};
//print使用了es6里的拼接字符串的方法
this.print = function(){
for (let i=0; i<items.length; i++){
console.log(`${items[i].element} - ${items[i].priority}`);
}
};
}
let priorityQueue = new PriorityQueue();
priorityQueue.enqueue("John", 2);
priorityQueue.enqueue("Jack", 1);
priorityQueue.enqueue("Camila", 1);
priorityQueue.enqueue("Maxwell", 2);
priorityQueue.enqueue("Ana", 3);
priorityQueue.print();
//=>
//打印出的結果
Jack - 1 //數組元素--優先級
Camila - 1
John - 2
Maxwell - 2
Ana - 3
在這個隊列的基礎上可以實現javascript中橋接模式的例子。本文算是一個獨立的javascript隊列的介紹,也作為橋接模式例子的背景方法。
javascript設計模式 第八章-橋接模式