-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementingaQueue.js
More file actions
103 lines (63 loc) · 2.33 KB
/
ImplementingaQueue.js
File metadata and controls
103 lines (63 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Queues are linear collections of objects that can be inserted and removed in a FIFO (first in, first out) manner.
// An example of a queue in real life and not strictly computing would simply be the dreaded waiting line, i.e.the first person in line is also the first one who gets out.
// Waiting Lines
// In this problem, we are going to be implementing our own enqueue, dequeue, and size methods for the queue constructor we are creating, so we should be able to create new instances of the Queue.
// The enqueue method takes in the item as a parameter, while the dequeue method does not.
// The size method simply returns the number of items in the queue.
// Wait, what?
// To enqueue an item into the queue means to insert an item into the back, or tail, of the queue.
// To dequeue an item means means to remove the item at the front, or head, of the queue.
// In a queue, we remove the item the least recently added.
// JavaScript Methodology
// Queues can be implemented in JavaScript using arrays.
// You can use the built in push or unshift functions in order to add items to the queue array as well as the shift or pop to remove them.
// As long as the tests pass, go for it!
var Queue = function() {
this.storage = {}
this.head = 0
this.tail = 0
// implement your Queue constructor here
};
Queue.prototype.enqueue = function(item) {
this.storage[this.tail] = item
this.tail++
// add item to the queue
};
Queue.prototype.dequeue = function() {
if (this.size()){
let removed = this.storage[this.head]
delete this.storage[this.head]
this.head++
return removed
}
// remove item from the front of the queue and return its value
};
Queue.prototype.size = function() {
return this.tail - this.head
// return number of items in queue so far
};
// const que = new Queue()
// que.enqueue("apple")
// que.enqueue("banana")
// que.enqueue("blueberry")
// que.dequeue()
// que.enqueue("blueberry")
// que.dequeue()
// console.log(que)
//REAL ONE
// class Queue {
// constructor(){
// this.list = [] }
// enqueue(item){
// this.list.unshift(item) }
// dequeue(){
// return this.list.pop() }
// size(){
// return this.list.length }
// }
let que = new Queue
que.enqueue("strawberry")
que.enqueue("banana")
que.enqueue("orange")
que.dequeue()
console.log(que)