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

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


Stack: Push Operation (টপে এলিমেন্ট যোগ করা)

Push মানে স্ট্যাকের টপে (অ্যারের শেষে) নতুন এলিমেন্ট যোগ করা। এটি স্ট্যাকের সবচেয়ে মৌলিক অপারেশন।

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

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

  isFull() {
    return this.container.length >= this.maxSize;
  }

  // Push Implementation
  push(element) {
    // স্ট্যাক ফুল চেক
    if (this.isFull()) {
      console.log("Stack Overflow! স্ট্যাকর সর্বোচ্চ সাইজে পৌঁছেছে।");
      return false;
    }
    // push() দিয়ে টপে যোগ করুন
    this.container.push(element);
    return true;
  }

  // Helper methods
  isEmpty() { return this.container.length === 0; }
  display() { console.log(this.container); }
}

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

const s = new Stack(2); // ম্যাক্স ২ এলিমেন্ট

s.display(); // []

s.push(10);  // true
s.push(20);  // true
s.display(); // [ 10, 20 ]

// ওভারফ্লো টেস্ট
s.push(30);  // "Stack Overflow!" + false
s.display(); // [ 10, 20 ] (অপরিবর্তিত)

আউটপুট ব্যাখ্যা

[]
[ 10, 20 ]
Stack Overflow! স্ট্যাকর সর্বোচ্চ সাইজে পৌঁছেছে।
[ 10, 20 ]

ক্যাপাসিটি ২, তাই ৩য় এলিমেন্ট (৩০) যোগ হয়নি।

Overflow Handling Strategies

// ১. Throw Error (Strict)
push(element) {
  if (this.isFull()) throw new Error("Stack Overflow");
  this.container.push(element);
}

// ২. Return Boolean (Simple)
push(element) {
  if (this.isFull()) return false;
  this.container.push(element);
  return true;
}

// ৩. Auto-resize (Dynamic Stack)
push(element) {
  if (this.isFull()) {
    this.maxSize *= 2; // ডাবল করুন
    // অথবা: this.maxSize = this.container.length + 10;
  }
  this.container.push(element);
  return true;
}

// ৪. Silent Ignore (Not Recommended)
push(element) {
  if (!this.isFull()) this.container.push(element);
}

Push Operation Complexity

  • Time: O(1) Amortized (অ্যারে রিসাইজ কম হলে)۔
  • Space: O(1) إضافی।

বাস্তব ব্যবহার: Undo Functionality

class UndoManager {
  constructor(maxHistory = 50) {
    this.history = new Stack(maxHistory);
    this.currentState = null;
  }

  setState(state) {
    if (this.currentState !== null) {
      this.history.push(this.currentState);
    }
    this.currentState = state;
  }

  undo() {
    if (this.history.isEmpty()) return null;
    const previous = this.history.pop();
    this.currentState = previous;
    return previous;
  }
}

// ব্যবহার
const undo = new UndoManager();
undo.setState("Draft 1");
undo.setState("Draft 2");
undo.setState("Draft 3");
console.log(undo.undo()); // "Draft 2"
console.log(undo.undo()); // "Draft 1"
  1. জাভাস্ক্রিপ্ট DOM কী?

  2. JavaScript-এ Stack ডেটা স্ট্রাকচার: LIFO নীতি এবং সম্পূর্ণ বাস্তবায়ন

  3. জাভাস্ক্রিপ্টে কিউ (Queue-এ) এলিমেন্ট যোগ করা (Enqueue)

  4. জাভাস্ক্রিপ্টে স্ট্যাক (Stack) বাস্তবায়ন