แม้อาร์เรย์จะมีฟังก์ชันคิวครบแล้ว มาสร้างคลาส Queue เอง ฟังก์ชันที่ต้องมี:
enqueue(element): เพิ่มสมาชิกในคิวdequeue(): นำสมาชิกออกจากคิวpeek(): ดูสมาชิกหัวคิวisFull(): ตรวจสอบเต็มหรือไม่isEmpty(): ตรวจสอบว่างหรือไม่clear(): ล้างทั้งหมดdisplay(): แสดงเนื้อหา
เริ่มด้วย constructor รับขนาดสูงสุด และฟังก์ชันช่วย display, isEmpty, isFull
ตัวอย่าง
class Queue {
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;
}
}
isFull ตรวจสอบความยาวเท่าหรือเกิน maxSize, isEmpty ตรวจสอบความยาวเป็น 0