কম্পিউটার টিউটোরিয়াল

জাভাস্ক্রিপ্টে PriorityQueue-এ Peek অপারেশন


PriorityQueue: Peek Operation (সর্বোচ্চ প্রায়োরিটিওয়ালা এলিমেন্ট দেখা)

Peek মানে প্রায়োরিটি কিউর সর্বোচ্চ প্রায়োরিটিওয়ালা এলিমেন্টটি রিমুভ না করে শুধু মান রিটার্ন করা। আমাদের ইমপ্লিমেন্টেশনে সর্বোচ্চ প্রায়োরিটি 지닌 এলিমেন্ট অ্যারের শেষে থাকে।

Peek মেথড ইমপ্লিমেন্টেশন

class PriorityQueue {
  constructor(maxSize = 10) {
    this.maxSize = maxSize;
    this.container = [];
  }

  isEmpty() {
    return this.container.length === 0;
  }

  // Peek Implementation
  peek() {
    if (this.isEmpty()) {
      console.log("Queue Underflow! কিউ খালি।");
      return undefined;
    }
    // সর্বোচ্চ প্রায়োরিটি = শেষ এলিমেন্ট (সর্টেড অর্ডার অনুযায়ী)
    return this.container[this.container.length - 1].data;
  }

  // ... enqueue, dequeue, clear, display ...
}

টেস্টিং উদাহরণ

const pq = new PriorityQueue(5);

pq.enqueue("Low", 1);
pq.enqueue("Medium", 5);
pq.enqueue("High", 10);

console.log("Peek:", pq.peek()); // "High" (সর্বোচ্চ প্রায়োরিটি)
pq.display(); 
// [ { data: 'Low', priority: 1 }, 
//   { data: 'Medium', priority: 5 }, 
//   { data: 'High', priority: 10 } ]

// Peek কিউর কন্টেন্ট বা সাইজ পরিবর্তন করে না
console.log("Size after peek:", pq.size()); // 3

Peek vs Dequeue

অপারেশন কাজ রিটার্ন কিউর সাইজ
peek() সর্বোচ্চ প্রায়োরিটিওয়ালা এলিমেন্ট দেখায় এলিমেন্টের ডেটা (data) অপরিবর্তিত
dequeue() সর্বোচ্চ প্রায়োরিটিওয়ালা এলিমেন্ট সরিয়ে ফেলে সরানো এলিমেন্টের ডেটা ১ কমে যায়

ব্যবহার ক্ষেত্র

  • নেক্সট হাই-প্রায়োরিটি টাস্ক চেক করা (এক্সিকিউশন ছাড়া)।
  • UI-এ "Next Critical Task" দেখানো।
  • কন্ডিশনাল প্রসেসিং: প্রায়োরিটি থ্রেশহোল্ড চেক করে ডিকিউ ডিসাইড।
  • মনিটরিং/লগিং: কিউর হেড ইনস্পেক্ট।

Edge Case: Empty Queue

peek() {
  if (this.isEmpty()) {
    // Production: Throw error
    throw new Error("PriorityQueue Underflow: Cannot peek empty queue");
    
    // Simple: Return undefined
    // return undefined;
  }
  return this.container[this.container.length - 1].data;
}
  1. জাভাস্ক্রিপ্টে PriorityQueue-এ Dequeue (Remove) অপারেশন

  2. জাভাস্ক্রিপ্টে লিংকড লিস্ট থেকে এলিমেন্ট রিমুভ করা

  3. জাভাস্ক্রিপ্টে লিংকড লিস্টে এলিমেন্ট যোগ করা (Insert)

  4. জাভাস্ক্রিপ্ট ব্যবহার করে ডাবল লিংকড লিস্ট থেকে এলিমেন্ট সরানো