คลาสจะมีฟังก์ชันดังนี้:
enqueue(element): เพิ่มสมาชิกในคิวdequeue(): นำสมาชิกออกจากคิวpeek(): ดูสมาชิกหัวคิวisFull(): ตรวจสอบเต็มหรือไม่isEmpty(): ตรวจสอบว่างหรือไม่clear(): ล้างทั้งหมดdisplay(): แสดงเนื้อหา
เริ่มด้วย constructor รับขนาดสูงสุด และฟังก์ชันช่วย display, isEmpty, isFull ต้องกำหนดโครงสร้างเพิ่มใน prototype สำหรับเก็บ priority และ data ของแต่ละโหนด ใช้อาร์เรย์เหมือน Stack
ตัวอย่าง
class PriorityQueue {
constructor(maxSize) {
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize;
this.container = [];
}
display() {
console.log(this.container);
}
isEmpty() {
return this.container.length === 0;
}
isFull() {
return this.container.length >= this.maxSize;
}
}
// Inner class สำหรับสร้างโหนดในคิว
// แต่ละ element มี data และ priority
PriorityQueue.prototype.Element = class {
constructor (data, priority) {
this.data = data;
this.priority = priority;
}
}
isFull ตรวจสอบความยาวเท่าหรือเกิน maxSize, isEmpty ตรวจสอบความยาวเป็น 0