Skip to content

Commit 738edaa

Browse files
authored
Create 02_Create a Stack Class.md
1 parent cb7a20e commit 738edaa

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
Although you can use arrays to create stacks, sometimes it is best to limit the amount of control we have with our stacks.
2+
Apart from the push and pop method, stacks have other useful methods.
3+
Let's add a `peek`, `isEmpty`, and `clear` method to our stack class.
4+
5+
Write a `push` method that pushes an element to the top of the stack,
6+
a `pop` method that removes the element on the top of the stack,
7+
a `peek` method that looks at the first element in the stack, an `isEmpty` method that checks if the stack is empty,
8+
and a `clear` method that removes all elements from the stack.
9+
Normally stacks don't have this, but we've added a print helper method that console logs the collection.
10+
11+
12+
```js
13+
function Stack() {
14+
var collection = [];
15+
this.print = function() {
16+
console.log(collection);
17+
};
18+
// Only change code below this line
19+
this.push = function(el) {
20+
collection.push(el);
21+
}
22+
23+
this.pop = function() {
24+
return collection.pop()
25+
}
26+
27+
this.peek = function() {
28+
return collection[collection.length - 1]
29+
}
30+
31+
this.isEmpty = function() {
32+
return (collection.length === 0);
33+
}
34+
35+
this.clear = function() {
36+
collection = [];
37+
}
38+
// Only change code above this line
39+
}
40+

0 commit comments

Comments
 (0)