--- id: 587d8250367417b2b2512c5f title: Create a Stack Class challengeType: 1 forumTopicId: 301633 localeTitle: Создать класс стека --- ## Description
В последнем разделе мы говорили о том, что такое стек и как мы можем использовать массив для представления стека. В этом разделе мы создадим собственный класс стека. Хотя вы можете использовать массивы для создания стеков, иногда лучше ограничивать количество контроля, которое у нас есть с нашими стопами. Помимо метода push и pop , у стеков есть и другие полезные методы. Давайте добавим peek , isEmpty и clear метод в наш класс стека. Инструкции Напишите метод push который подталкивает элемент к вершине стека, метод pop который удаляет элемент в верхней части стека, метод peek который смотрит на первый элемент в стеке, метод isEmpty который проверяет, стек пуст и clear метод, который удаляет все элементы из стека. Обычно у стеков это не так, но мы добавили метод вспомогательной print котором консоль регистрирует коллекцию.
## Instructions
Write a push method that pushes an element to the top of the stack, a pop method that removes the element on the top of the stack, a peek method that looks at the first element in the stack, an isEmpty method that checks if the stack is empty, and a clear method that removes all elements from the stack. Normally stacks don't have this, but we've added a print helper method that console logs the collection.
## Tests
```yml tests: - text: Your Stack class should have a push method. testString: assert((function(){var test = new Stack(); return (typeof test.push === 'function')}())); - text: Your Stack class should have a pop method. testString: assert((function(){var test = new Stack(); return (typeof test.pop === 'function')}())); - text: Your Stack class should have a peek method. testString: assert((function(){var test = new Stack(); return (typeof test.peek === 'function')}())); - text: Your Stack class should have a isEmpty method. testString: assert((function(){var test = new Stack(); return (typeof test.isEmpty === 'function')}())); - text: Your Stack class should have a clear method. testString: assert((function(){var test = new Stack(); return (typeof test.clear === 'function')}())); - text: The peek method should return the top element of the stack testString: assert((function(){var test = new Stack(); test.push('CS50'); return (test.peek() === 'CS50')}())); - text: The pop method should remove and return the top element of the stack testString: assert((function(){var test = new Stack(); test.push('CS50'); return (test.pop() === 'CS50');}())); - text: The isEmpty method should return true if a stack does not contain any elements testString: assert((function(){var test = new Stack(); return test.isEmpty()}())); - text: The clear method should remove all element from the stack testString: assert((function(){var test = new Stack(); test.push('CS50'); test.clear(); return (test.isEmpty())}())); ```
## Challenge Seed
```js function Stack() { var collection = []; this.print = function() { console.log(collection); }; // Only change code below this line // Only change code above this line } ```
## Solution
```js class Stack { constructor() { this.collection = []; } print() { console.log(this.collection); } push(val) { this.collection.push(val); } pop() { return this.collection.pop(); } peek() { return this.collection[this.collection.length - 1]; } isEmpty() { return this.collection.length === 0; } clear() { return (this.collection.length = 0); } } ```