-
Notifications
You must be signed in to change notification settings - Fork 1
/
room.js
48 lines (41 loc) · 973 Bytes
/
room.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
const { v4: uuidv4 } = require("uuid");
// the maximun number of people allowed in a room
const ROOM_MAX_CAPACITY = 2;
/**
* roomState = [{id: roomid}, users: number]
*/
class Room {
constructor() {
this.roomsState = [];
}
joinRoom() {
return new Promise((resolve) => {
for (let i = 0; i < this.roomsState.length; i++) {
if (this.roomsState[i].users < ROOM_MAX_CAPACITY) {
this.roomsState[i].users++;
return resolve(this.roomsState[i].id);
}
}
// else generate a new room id
const newID = uuidv4();
this.roomsState.push({
id: newID,
users: 1,
});
return resolve(newID);
});
}
leaveRoom(id) {
this.roomsState = this.roomsState.filter((room) => {
if (room.id === id) {
if (room.users === 1) {
return false;
} else {
room.users--;
}
}
return true;
});
}
}
module.exports = Room;