-
Notifications
You must be signed in to change notification settings - Fork 0
/
results.html
238 lines (220 loc) · 8.61 KB
/
results.html
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
<head>
<link rel="stylesheet" type="text/css" href="stylesheets/shared_style.css">
</head>
<body onload="fetchResults();">
<div class="container">
<div id="displayRawData">
<!-- raw data here -->
</div>
<div id="displayWinner">
<!-- Winner Here -->
</div>
<div id="notice">
<!-- Notice Information -->
</div>
</div>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.14/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.14/firebase-database.js"></script>
<!-- JQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyByAyDFaMNDwKpfRhAQPk0B70ILYst-oS4",
authDomain: "ballot-d933a.firebaseapp.com",
databaseURL: "https://ballot-d933a.firebaseio.com",
projectId: "ballot-d933a",
storageBucket: "ballot-d933a.appspot.com",
messagingSenderId: "227086842486",
appId: "1:227086842486:web:849611a5373b9fc0ce7d57",
measurementId: "G-Y8X924EG6M"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
function fetchResults(){
var urlParams = new URLSearchParams(window.location.search);
var token = urlParams.get('token').toUpperCase();
//TODO make update in realtime
firebase.database().ref('ballots/' + token).once('value').then(function(snapshot) {
var ballotType = (snapshot.val() && snapshot.val().ballotType);
if(ballotType == null){ ballotTypeError(); }
var candidates = (snapshot.val() && snapshot.val().candidateDict);
if(candidates == null){ candidatesError(); }
var numVotes = (snapshot.val() && snapshot.val().numVotes);
if(numVotes == null){ numVotesError(); }
if(ballotType == "First Past the Post" || ballotType == "Approval Voting"){
barChart(Object.keys(candidates).map(function(key){
return candidates[key];
}), Object.keys(candidates))
$("#displayWinner").append(
'<h1>The Winnner is: ' + getWinner(candidates) + '</h1>');
}
else{ //ranked choice
for(key_i in candidates){
for(key_j in candidates[key_i]){
printBallot([key_i].concat(candidates[key_i][key_j]));
}
}
$("#displayRawData").append('<p>'+numVotes+' ballots cast total</p>');
$("#displayWinner").append(
'<h1>The Winnner is: ' + getWinnerRanked(candidates, numVotes) + '</h1>');
}
});
}
function getVotes(name, num){
return '<p>' + name + ':' + num + '</p>'
}
function getWinner(candidates){
return Object.keys(candidates).reduce(function(a, b) {
return candidates[a] > candidates[b] ? a : b
});
}
function barChart(data, labels){
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('height', `${500}px`);
svg.setAttribute('width', `${500}px`);
svg.setAttribute('viewBox', `0 0 500 500`);
function generateChart(data, labels){
const barChartElems = [];
const create = (data, labels) => {
var max = Math.max.apply(Math, data);
const scale = 400/max;
data.forEach((entry, index) => {
const bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
bar.setAttribute('x', index * (500 / data.length));
var height = entry*scale;
bar.setAttribute('y', 450 - height);
bar.setAttribute('height', `${height}px`);
bar.setAttribute('width', `${500 / data.length}px`);
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.textContent = labels[index] + ': ' + entry;
text.setAttribute('x', (index+0.5) * (500 / data.length));
text.setAttribute('y', 475);
svg.appendChild(bar);
svg.appendChild(text);
barChartElems.push(bar);
});
};
return create(data, labels);
}
document.getElementById("displayRawData").appendChild(svg);
const updateChart = generateChart(data, labels);
}
function printBallot(ballot){
var text = '<p>One Ballot cast for ' + ballot + '</p>';
$("#displayRawData").append(text);
}
function getWinnerRanked(candidatesOriginal, numVotes){
var counter = 0;
var majorityWinner = "";
var majorityLosers = [];
var candidates = JSON.parse(JSON.stringify(candidatesOriginal));
var iterations = 5;
for(var i = 0; i < iterations; ++i){
var res = simpleMajorityRanked(candidates, numVotes);
majorityWinner = res[0];
majorityLosers = res[1];
if(majorityWinner != ""){
return majorityWinner;
}
// else
for(key_i in majorityLosers){
var loser = majorityLosers[key_i];
//TODO append message to #notices if this is first tie
for(key_j in candidates[loser]){
var vote = candidates[loser][key_j]
//reaportion
var nextCandidate = vote[0];
if(nextCandidate == null){ continue; }
while(nextCandidate != null && candidates[nextCandidate] == 0){
//while vote will be reaportioned to eliminated candidate go to next choice
vote.splice(0,1);
nextCandidate = vote[0];
}
if(nextCandidate == null){ continue; }
vote.splice(0,1); //remove first element
candidates[nextCandidate]['newVote' + counter++] = vote;
}
candidates[loser] = 0; //clear votes from loser
}
// check if all candidateds are eliminated
if(allEliminated(candidates)){
$("#notice").append(
'<p>All candidates eliminated</p>'
);
// reaportion all to 2nd choice
candidates = allSecondChoice(candidatesOriginal);
candidatesOriginal = candidates;
}
}
}
function simpleMajorityRanked(candidates, numTotalVotes){
var majority = Math.floor(numTotalVotes / 2.0);
var leastVotes = Number.MAX_SAFE_INTEGER;
var leastCandidates = [];
for(var key in candidates){
var numVotes = 0;
if(candidates[key] != 0){
numVotes = Object.keys(candidates[key]).length;
if(numVotes > majority){
return [key, []]
}
// we only care about reapropriating votes if a candidate got votes
if(numVotes == leastVotes){
leastCandidates.push(key);
}
else if(numVotes < leastVotes){
leastVotes = numVotes;
leastCandidates = [key];
}
}
}
return ["", leastCandidates]
}
function allEliminated(candidates){
for(key in candidates){
if(candidates[key] != 0){ return false; }
}
return true;
}
function allSecondChoice(candidates){
var counter = 0;
var candidatesCopy = {};
for(key_i in candidates){
var candidate = candidates[key_i];
if(candidatesCopy[key_i] == null){
candidatesCopy[key_i] = {};
}
if(candidate == 0){ continue; }
for(key_j in candidate){
var vote = candidates[key_i][key_j];
var nextCandidate = vote[0];
if(nextCandidate == null){ continue; }
while(nextCandidate != null && candidates[nextCandidate] == 0){
//while vote will be reaportioned to eliminated candidate go to next choice
vote.splice(0,1);
nextCandidate = vote[0];
}
if(nextCandidate == null){ continue; }
vote.splice(0,1); //remove first element
if(candidatesCopy[nextCandidate] == null){
candidatesCopy[nextCandidate] = {};
}
candidatesCopy[nextCandidate]['newVote' + counter++] = vote;
}
}
return convertEmptyToZereos(candidatesCopy);
}
function convertEmptyToZereos(candidates){
for(key in candidates){
if(Object.keys(candidates[key]).length == 0){
candidates[key] = 0;
}
}
return candidates;
}
</script>
</body>