Lớp sẽ có các hàm:
enqueue(element): Thêm phần tử vào queuedequeue(): Xóa phần tử từ queuepeek(): Trả về phần tử đầu queueisFull(): Kiểm tra đạt giới hạnisEmpty(): Kiểm tra queue rỗngclear(): Xóa tất cảdisplay(): Hiển thị nội dung
Định nghĩa lớp đơn giản với constructor nhận maxSize và helper function. Cũng định nghĩa cấu trúc khác trên prototype PriorityQueue để lưu priority và data cho mỗi node. Tương tự Stack, dùng mảng triển khai Priority Queue.
Ví dụ - Khởi tạo PriorityQueue
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; } } PriorityQueue.prototype.Element = class { constructor (data, priority) { this.data = data; this.priority = priority; } }
isFull kiểm tra length >= maxSize. isEmpty kiểm tra length === 0. Các hàm tiếp theo sẽ vào lớp PriorityQueue.