작은 도우미 기능이 거의 없는 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;
}
} 여기 isFull이 있습니다. 함수는 컨테이너의 길이가 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 ]