यहां 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; } enqueue(data, priority) { // जांचें कि क्यू भरा हुआ है या नहीं if (this.isFull()) { console.log("Queue Overflow!"); return; } let currElem = new this.Element(data, priority); let addedFlag = false; // चूंकि हम एलिमेंट्स को अंत में जोड़ना चाहते हैं, हम बस उन्हें पुश करेंगे। for (let i = 0; i < this.container.length; i++) { if (currElem.priority < this.container[i].priority) { this.container.splice(i, 0, currElem); addedFlag = true; break; } } if (!addedFlag) { this.container.push(currElem); } } dequeue() { // जांचें कि खाली है या नहीं if (this.isEmpty()) { console.log("Queue Underflow!"); return; } return this.container.pop(); } peek() { if (isEmpty()) { console.log("Queue Underflow!"); return; } return this.container[this.container.length - 1]; } clear() { this.container = []; } } // एक इनर क्लास बनाएं जिसका उपयोग हम क्यू में नए नोड्स बनाने के लिए करेंगे // प्रत्येक एलिमेंट में कुछ डेटा और एक प्रायोरिटी होती है PriorityQueue.prototype.Element = class { constructor(data, priority) { this.data = data; this.priority = priority; } };