-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
97 lines (85 loc) · 2.24 KB
/
index.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
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
var users = [];
var result = {};
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('username', (username) => {
users.push(username);
io.emit('usernames', users);
});
socket.on('vote', (username, vote) => {
result[username] = vote;
if (Object.keys(result).length == users.length) {
var sum = 0;
var valids = 0;
var qMarks = 0;
var votes = Object.values(result);
for (index in votes) {
if (votes[index] !== "?") {
valids++;
sum += parseFloat(votes[index]);
} else {
qMarks++;
}
}
io.emit('vote-result', (sum / valids).toFixed(1), votes);
result = {};
} else {
var voters = Object.keys(result);
var awaiting = [];
for (index in users) {
if (voters.indexOf(users[index]) == -1) {
awaiting.push(users[index]);
}
}
io.emit('waiting-on', awaiting);
}
});
socket.on('force-vote', (username) => {
var sum = 0;
var valids = 0;
var qMarks = 0;
var votes = Object.values(result);
for (index in votes) {
if (votes[index] !== "?") {
valids++;
sum += parseFloat(votes[index]);
} else {
qMarks++;
}
}
io.emit('vote-result', (sum / valids).toFixed(1), votes);
result = {};
console.log(username + ' forced the votes!');
});
socket.on('clear-vote', (username) => {
result = {};
console.log(username + ' cleared the votes!');
});
socket.on('exit', (username) => {
while (users.indexOf(username) > -1) {
users.splice(users.indexOf(username), 1);
}
io.emit('usernames', users);
});
socket.on('clear', (username) => {
result = {};
users = [];
io.emit('vote-cleared');
console.log(username + ' cleared the votes!');
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
server.listen(3000, () => {
console.log('listening on *:3000');
});