File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ //Language: Javascript
2+ //Author: Uddesh Jain
3+ //Github: https://github.com/UddeshJain
4+ class Queue {
5+ constructor ( ) {
6+ this . _storage = { }
7+ this . _length = 0
8+ this . _headIndex = 0
9+ }
10+ /*
11+ * Enqueues a new value at the end of the Queue
12+ * @param {* } value - the value to enqueue
13+ */
14+ enqueue ( value ) {
15+ if ( value ) {
16+ this . _storage [ this . _length + this . _headIndex ] = value
17+ this . _length ++
18+ }
19+ }
20+ /*
21+ * Dequeues the value from the begning of the Queue and return it
22+ * @retuen {*} value - the first and oldest value in the Queue
23+ */
24+ dequeue ( ) {
25+ if ( this . _length ) {
26+ const firstValue = this . _storage [ this . _headIndex ]
27+ delete this . _storage [ this . _headIndex ]
28+ this . _length --
29+ this . _headIndex ++
30+ return firstValue
31+ }
32+ }
33+ }
34+
35+ const myQueue = new Queue ( ) // Creates new instance
36+ myQueue . enqueue ( 'zero' ) // Adds the value in the end of Queue
37+ myQueue . dequeue ( ) // Removes the value from first position of Queue
38+ myQueue . enqueue ( 'Two' ) // Adds the value in the end of Queue
Original file line number Diff line number Diff line change 1+ //Language: Javascript
2+ //Author: Uddesh Jain
3+ //Github: https://github.com/UddeshJain
4+ class Stack {
5+ constructor ( ) {
6+ this . _storage = { }
7+ this . _length = 0
8+ }
9+ /*
10+ * Adds a new value in the end of the Stack
11+ * @param {* } value - the value to push
12+ */
13+ push ( value ) {
14+ if ( value ) {
15+ this . _storage [ this . _length ] = value
16+ this . _length ++
17+ }
18+ }
19+ /*
20+ * Removes the value at the end of stack and returns it
21+ * @return {* } the last and newest value in the Stack
22+ */
23+ pop ( ) {
24+ if ( this . _length ) {
25+ const lastValue = this . _storage [ this . _length - 1 ]
26+ this . _storage [ this . _length - 1 ] = undefined
27+ this . _length --
28+ return lastValue
29+ }
30+ }
31+ /*
32+ * Returns the value at the end of Stack without removing it
33+ * @return {* } the last and newest value in Stack
34+ */
35+ peek ( ) {
36+ return lastValue = this . _storage [ this . _storage - 1 ]
37+ }
38+ }
39+
40+ const myStack = new Stack ( ) // Creates new instance
41+ myStack . push ( 'First' ) // Adds the value to the Stack
42+ myStack . pop ( ) // Removes the last value in Stack
43+ myStack . peek ( ) // Returns the last value in Stack
You can’t perform that action at this time.
0 commit comments