File tree Expand file tree Collapse file tree 3 files changed +73
-6
lines changed
lib/data-structures/stacks Expand file tree Collapse file tree 3 files changed +73
-6
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Data structure that adds and remove elements in a last-in, first-out (LIFO) fashion
3+ */
4+ class Stack {
5+ constructor ( ) {
6+ this . input = [ ] ;
7+ }
8+
9+ /**
10+ * Add element into the stack
11+ * Runtime: O(1)
12+ * @param {any } element
13+ */
14+ add ( element ) {
15+ this . input . push ( element ) ;
16+ return this ;
17+ }
18+
19+ /**
20+ * Remove element from the stack
21+ * Runtime: O(1)
22+ */
23+ remove ( ) {
24+ return this . input . pop ( ) ;
25+ }
26+
27+ /**
28+ * Size of the queue
29+ */
30+ get size ( ) {
31+ return this . input . length ;
32+ }
33+ }
34+
35+ // aliases
36+ Stack . prototype . push = Stack . prototype . add ;
37+ Stack . prototype . pop = Stack . prototype . remove ;
38+
39+ module . exports = Stack ;
40+
Original file line number Diff line number Diff line change 1+ const LinkedList = require ( '../linked-lists/linked-list' ) ;
2+
3+ /**
4+ * Data structure that adds and remove elements in a last-in, first-out (LIFO) fashion
5+ */
16class Stack {
27 constructor ( ) {
3- this . input = [ ] ;
8+ this . input = new LinkedList ( ) ;
49 }
510
6- push ( element ) {
7- this . input . push ( element ) ;
11+ /**
12+ * Add element into the stack
13+ * Runtime: O(1)
14+ * @param {any } element
15+ */
16+ add ( element ) {
17+ this . input . addLast ( element ) ;
818 return this ;
919 }
1020
11- pop ( ) {
12- return this . input . pop ( ) ;
21+ /**
22+ * Remove element from the stack
23+ * Runtime: O(1)
24+ */
25+ remove ( ) {
26+ return this . input . removeLast ( ) ;
27+ }
28+
29+ /**
30+ * Size of the queue
31+ */
32+ get size ( ) {
33+ return this . input . size ;
1334 }
1435}
1536
37+ // aliases
38+ Stack . prototype . push = Stack . prototype . add ;
39+ Stack . prototype . pop = Stack . prototype . remove ;
40+
1641module . exports = Stack ;
1742
Original file line number Diff line number Diff line change @@ -9,8 +9,9 @@ describe('Stack', function () {
99
1010 describe ( '#push' , ( ) => {
1111 it ( 'should push an element to the stack' , ( ) => {
12+ expect ( stack . size ) . toEqual ( 0 ) ;
1213 stack . push ( 1 ) ;
13- expect ( stack . input ) . toEqual ( [ 1 ] ) ;
14+ expect ( stack . size ) . toEqual ( 1 ) ;
1415 } ) ;
1516 } ) ;
1617
@@ -23,6 +24,7 @@ describe('Stack', function () {
2324 it ( 'should get last element entered' , ( ) => {
2425 expect ( stack . pop ( ) ) . toEqual ( 'b' ) ;
2526 expect ( stack . pop ( ) ) . toEqual ( 'a' ) ;
27+ expect ( stack . pop ( ) ) . toEqual ( undefined ) ;
2628 } ) ;
2729 } ) ;
2830} ) ;
You can’t perform that action at this time.
0 commit comments