Files: 028237b4b26db208a93b7399ed9575c6608b1999 / position / sync / chooseOneResults.js
1789 bytesRaw
1 | var getMsgContent = require('../../lib/getMsgContent') |
2 | var ChooseOne = require('../../poll/sync/chooseOne') |
3 | const PositionChoiceError = require('../../errors/sync/positionChoiceError') |
4 | const PositionLateError = require('../../errors/sync/positionLateError') |
5 | |
6 | // Expects `poll` and `position` objects passed in to be of shape: |
7 | // { |
8 | // key, |
9 | // value: { |
10 | // content: {...}, |
11 | // timestamp: ... |
12 | // author: ... |
13 | // } |
14 | // } |
15 | // |
16 | // postions must be of the correct type ie: type checked by the caller. |
17 | module.exports = function chooseOneResults ({positions, poll}) { |
18 | var results = getMsgContent(poll) |
19 | .details |
20 | .choices |
21 | .map(choice => { |
22 | return { |
23 | choice, |
24 | voters: {} |
25 | } |
26 | }) |
27 | |
28 | return positions.reduce(function (acc, position) { |
29 | const { author, content } = position.value |
30 | const { choice } = content.details |
31 | |
32 | if (isInvalidChoice({position, poll})) { |
33 | acc.errors.push(PositionChoiceError({position})) |
34 | return acc |
35 | } |
36 | |
37 | if (isPositionLate({position, poll})) { |
38 | acc.errors.push(PositionLateError({position})) |
39 | return acc |
40 | } |
41 | |
42 | deleteExistingVotesByAuthor({results: acc.results, author}) |
43 | acc.results[choice].voters[author] = position |
44 | |
45 | return acc |
46 | }, {errors: [], results}) |
47 | } |
48 | |
49 | // !!! assumes these are already sorted by time. |
50 | // modifies results passed in |
51 | function deleteExistingVotesByAuthor ({author, results}) { |
52 | results.forEach(result => { |
53 | if (result.voters[author]) { |
54 | delete result.voters[author] |
55 | } |
56 | }) |
57 | } |
58 | |
59 | function isInvalidChoice ({position, poll}) { |
60 | const { choice } = position.value.content.details |
61 | return choice >= poll.value.content.details.choices.length |
62 | } |
63 | |
64 | function isPositionLate ({position, poll}) { |
65 | return position.value.timestamp > poll.value.content.closesAt |
66 | } |
67 |
Built with git-ssb-web