-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueue.js
106 lines (86 loc) · 2.36 KB
/
Queue.js
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
104
105
106
class Queue {
constructor() {
this.queue = [];
}
update() {
if (this.isEmpty()) {
return;
}
const uniqueUsers = [...new Set(this.queue.map((item) => item.addedBy))];
if (uniqueUsers.length === 1) {
// If all songs are added by the same person, no need to reorganize
return;
}
const fairQueue = [];
let currentIndex = 0;
while (this.queue.length > 0) {
const currentUser = uniqueUsers[currentIndex];
const userSong = this.queue.find((item) => item.addedBy === currentUser);
if (userSong) {
fairQueue.push(userSong);
this.queue = this.queue.filter((item) => item !== userSong);
}
currentIndex = (currentIndex + 1) % uniqueUsers.length;
}
this.queue = fairQueue;
}
shift() {
if (this.isEmpty()) {
console.error("Queue is empty");
return;
}
return this.queue.shift();
}
push(element, person) {
if (!element || !person) {
console.error("Invalid input");
return;
}
const queueElement = {
addedBy: person,
song: element,
dateAdded: new Date(),
};
this.queue.push(queueElement);
this.update();
}
// push element to the front of the queue
unshift(element, person) {
if (!element || !person) {
console.error("Invalid input");
return;
}
const queueElement = {
addedBy: person,
song: element,
dateAdded: new Date(),
};
this.queue.unshift(queueElement);
this.update();
}
isEmpty() {
return this.queue.length === 0;
}
clear() {
this.queue = [];
}
getQueue() {
return this.queue;
}
jumpToIndex(index) {
if (index < 0 || index >= this.queue.length) {
console.error("Index out of bounds");
return;
}
this.queue.splice(0, index);
}
removeQueueElement(index) {
if (index < 0 || index >= this.queue.length) {
console.error("Index out of bounds");
return;
}
this.queue.splice(index, 1);
this.update();
}
}
module.exports = Queue;