พิจารณาคลาสสแต็กต่อไปนี้ใน Javascript ด้วยฟังก์ชันตัวช่วยเล็กๆ น้อยๆ
ตัวอย่าง
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;
}
} ที่นี่ เต็มแล้ว ฟังก์ชั่นเพียงตรวจสอบว่าความยาวของคอนเทนเนอร์เท่ากับหรือมากกว่า maxSize และส่งคืนตามนั้น ว่างเปล่า ฟังก์ชันตรวจสอบว่าขนาดของคอนเทนเนอร์เป็น 0
ในส่วนนี้ เราจะเพิ่มการดำเนินการ PUSH ในคลาสนี้ การผลักอิลิเมนต์ไปที่สแต็กหมายถึงการเพิ่มอิลิเมนต์ไว้ที่ด้านบนสุดของอาร์เรย์ เรากำลังทำให้ส่วนท้ายของคอนเทนเนอร์อาร์เรย์อยู่ด้านบนสุดของอาร์เรย์ เนื่องจากเราจะดำเนินการทั้งหมดที่เกี่ยวข้อง ดังนั้นเราจึงสามารถใช้ฟังก์ชันพุชได้ดังนี้ −
ตัวอย่าง
push(element) {
// Check if stack is full
if (this.isFull()) {
console.log("Stack Overflow!");
return;
}
this.container.push(element);
} คุณสามารถตรวจสอบว่าฟังก์ชันนี้ทำงานได้ดีหรือไม่โดยใช้ −
ตัวอย่าง
let s = new Stack(2); s.display(); s.push(10); s.push(20); s.push(30); s.display();
ผลลัพธ์
สิ่งนี้จะให้ผลลัพธ์ -
[] Stack Overflow! [ 10, 20 ]