-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.js
86 lines (71 loc) · 2.32 KB
/
state.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
var debug = require('debug')('Clack:state');
function State(io) {
this.io = io
this.pollingOpen = false;
this.choicesCount = 0;
this.votes = {};
this.counter = 0;
this.studentSubmit = {};
}
module.exports = State;
State.prototype.uniqueid = function() {
this.counter++;
return this.counter;
}
State.prototype.openPolls = function(choicesCount) {
debug('opening votes');
this.votes = {};
this.choicesCount = choicesCount;
this.studentSubmit = {};
this.pollingOpen = true;
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (i=0; i < choicesCount; i++) {
this.votes[alphabet[i]] = 0;
}
this.io.emit('pollingOpen', {choicesCount: choicesCount});
}
State.prototype.closePolls = function() {
debug('closing votes');
this.pollingOpen = false;
this.io.emit('pollingClose');
}
State.prototype.recordVote = function(vote, uniqueid) {
//if this user has never entered a vote before let's log it
if(!(uniqueid in this.studentSubmit)){
this.studentSubmit[uniqueid] = vote;
//if this vote has never been chosen before
if(!(vote in this.votes)){
this.votes[vote] = 1;
}
//if this vote has bee chose before
else{
this.votes[vote]++;
}
}
//if they have logged a vote before we need to update their new choice
else{
//get their previous submission which we will subtract the total count from later
previousChoice = this.studentSubmit[uniqueid];
//If the choice they made is not the same as the choice they have made before
// basically if they have made a new choice then do something
if(previousChoice != vote){
//update their key with their new vote choice
this.studentSubmit[uniqueid] = vote;
this.votes[previousChoice]--;
// If never chosen before
if(!(vote in this.votes)){
this.votes[vote] = 1;
}
//if this vote has bee chose before
else{
this.votes[vote]++;
}
}
}
// Now we need to update stats
debug(this.votes);
this.sendUpdate();
}
State.prototype.sendUpdate = function() {
this.io.emit('voteUpdate', {votes: this.votes});
}