-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpoll.js
More file actions
53 lines (44 loc) · 1.4 KB
/
poll.js
File metadata and controls
53 lines (44 loc) · 1.4 KB
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
// Example usage.
// var Poll = require('./poll');
// var myPoll = Poll(['up', 'down', 'left', 'right']);
// myPoll.vote('up', 'voter-a');
// myPoll.vote('down', 'voter-b');
// myPoll.vote('up', 'voter-a');
// var results = myPoll.close();
const Result = require('r-result');
const Ok = Result.Ok;
const Fail = Result.Fail;
// [String] -> fns
const Poll = function (options) {
const votes = options.reduce(function (votes, option) {
votes[option.toLowerCase()] = 0;
return votes;
}, Object.create(null));
const voters = [];
var open = true;
return {
// (String, String) -> bool
// Calling this function after the poll is closed is an error.
vote: function (option, voter) {
if (!open) {
throw new Error("Cannot vote on closed poll.");
}
option = option.toLowerCase();
if (typeof votes[option] !== "number") {
return Fail("no-option");
} else if (voters.indexOf(voter) !== -1) {
return Fail("already-voted");
} else {
votes[option] += 1;
voters.push(voter);
return Ok();
}
},
// Closes the poll, and transfers ownership of votes tally to caller.
close: function () {
open = false;
return votes;
}
};
};
module.exports = Poll;