|
1 | | -const { LinkedList: SinglyLinkedLists } = require('../LinkedList'); |
| 1 | +const { LinkedList: SLL } = require('../LinkedList'); |
2 | 2 |
|
3 | | -class Queue extendsSinglyLinkedLists{ |
| 3 | +class Queue { |
4 | 4 | constructor() {
|
5 | | - super(); |
6 | | - this.NotAllowed = 'Not Allowed'; |
| 5 | + this.data = this.getStorage(); |
7 | 6 | }
|
8 | 7 |
|
9 | | - enqueue(data) { |
10 | | - returnthis.addAtEnd(data); |
| 8 | + enqueue(element) { |
| 9 | + this.data.enqueue(element); |
11 | 10 | }
|
12 | 11 |
|
13 | 12 | dequeue() {
|
14 | | - const node = this.removeFromBeginning(); |
15 | | - return node ? node.data : node; |
| 13 | + return this.data.dequeue(); |
16 | 14 | }
|
17 | 15 |
|
18 | 16 | peek() {
|
19 | | - const node = this.getFirst(); |
20 | | - return node ? node.data : node; |
| 17 | + return this.data.peek(); |
21 | 18 | }
|
22 | 19 |
|
23 | 20 | length() {
|
24 | | - return this.size; |
| 21 | + return this.data.length(); |
25 | 22 | }
|
26 | 23 |
|
27 | 24 | destroy() {
|
28 | | - this.delete(); |
29 | | - } |
30 | | - |
31 | | - /** Override and throw error for other LL methods */ |
32 | | - addAtBeginning() { |
33 | | - throw new Error(this.NotAllowed); |
34 | | - } |
35 | | - |
36 | | - addAt() { |
37 | | - throw new Error(this.NotAllowed); |
38 | | - } |
39 | | - |
40 | | - removeFromEnd() { |
41 | | - throw new Error(this.NotAllowed); |
42 | | - } |
43 | | - |
44 | | - getLast() { |
45 | | - throw new Error(this.NotAllowed); |
46 | | - } |
47 | | - |
48 | | - getAt() { |
49 | | - throw new Error(this.NotAllowed); |
50 | | - } |
51 | | - |
52 | | - removeAt() { |
53 | | - throw new Error(this.NotAllowed); |
| 25 | + return this.data.destroy(); |
| 26 | + } |
| 27 | + |
| 28 | + // eslint-disable-next-line class-methods-use-this |
| 29 | + getStorage() { |
| 30 | + // encapsulating the internal implementation here |
| 31 | + const storage = new SLL(); |
| 32 | + |
| 33 | + return { |
| 34 | + enqueue(element) { |
| 35 | + return storage.addAtEnd(element); |
| 36 | + }, |
| 37 | + dequeue() { |
| 38 | + const node = storage.removeFromBeginning(); |
| 39 | + return node ? node.data : node; |
| 40 | + }, |
| 41 | + peek() { |
| 42 | + const node = storage.getFirst(); |
| 43 | + return node ? node.data : node; |
| 44 | + }, |
| 45 | + length() { |
| 46 | + return storage.size; |
| 47 | + }, |
| 48 | + destroy() { |
| 49 | + storage.delete(); |
| 50 | + }, |
| 51 | + }; |
54 | 52 | }
|
55 | 53 | }
|
56 | 54 |
|
|
0 commit comments