Xét lớp Stack đơn giản:
Ví dụ - Lớp Stack cơ bản
class Stack { 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 >= maxSize; } push(element) { if (this.isFull()) { console.log("Stack Overflow!"); return; } this.container.push(element); } pop() { if (this.isEmpty()) { console.log("Stack Underflow!"); return; } this.container.pop(); } }
Thêm thao tác PEEK: lấy giá trị đỉnh mảng (phần tử cuối).
peek() { if (this.isEmpty()) { console.log("Stack Underflow!"); return; } return this.container[this.container.length - 1]; }
Kiểm tra:
Ví dụ
let s = new Stack(2); s.peek(); s.push(10); console.log(s.peek());
Kết quả
Stack Underflow! 10
Peek stack rỗng báo Underflow. Sau push(10), peek trả về 10.