জাভাস্ক্রিপ্টে একটি সাধারণ স্ট্যাক ক্লাস বিবেচনা করুন৷
উদাহরণ
class Stack {
constructor(maxSize) {
// Set default max size if not provided
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize; // Init an array that'll contain the stack values.
this.container = [];
}
// A method just to see the contents while we develop this class
display() {
console.log(this.container);
}
// Checking if the array is empty
isEmpty() {
return this.container.length === 0;
}
// Check if array is full
isFull() {
return this.container.length >= maxSize;
}
push(element) {
// Check if stack is full
if (this.isFull()) {
console.log("Stack Overflow!");
return;
}
this.container.push(element);
}
pop() {
// Check if empty
if (this.isEmpty()) {
console.log("Stack Underflow!");
return;
}
this.container.pop();
}
peek() {
if (isEmpty()) {
console.log("Stack Underflow!");
return;
}
return this.container[this.container.length - 1];
}
} এখানে Full ফাংশন শুধু পরীক্ষা করে যে একটি পাত্রের দৈর্ঘ্য maxSize এর সমান বা তার বেশি এবং সেই অনুযায়ী রিটার্ন করে। খালি আছে ধারকটির আকার 0 হলে ফাংশন পরীক্ষা করে। পুশ এবং পপ ফাংশনগুলি যথাক্রমে স্ট্যাক থেকে নতুন উপাদান যোগ এবং অপসারণ করতে ব্যবহৃত হয়।
এই বিভাগে, আমরা এই ক্লাসে CLEAR অপারেশন যোগ করতে যাচ্ছি। আমরা কন্টেইনার উপাদানটিকে একটি খালি অ্যারেতে পুনরায় বরাদ্দ করে বিষয়বস্তু পরিষ্কার করতে পারি। উদাহরণস্বরূপ,
উদাহরণ
clear() {
this.container = [];
} আপনি −
ব্যবহার করে এই ফাংশনটি ভাল কাজ করছে কিনা তা পরীক্ষা করতে পারেনউদাহরণ
let s = new Stack(2); s.push(10); s.push(20); s.display(); s.clear(); s.display();
আউটপুট
এটি আউটপুট দেবে −
[10, 20] []