Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

สร้าง Priority Queue ใน JavaScript: คลาสพื้นฐาน


คลาสจะมีฟังก์ชันดังนี้:

  • 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