Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tạo Priority Queue trong JavaScript

Lớp sẽ có các hàm:

  • enqueue(element): Thêm phần tử vào queue
  • dequeue(): Xóa phần tử từ queue
  • peek(): Trả về phần tử đầu queue
  • isFull(): Kiểm tra đạt giới hạn
  • isEmpty(): Kiểm tra queue rỗng
  • clear(): 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.