git ssb

0+

Piet / ssb-loomio



Tree: 89d04b0f0784096d39f86b2f8cd93579dabc8643

Files: 89d04b0f0784096d39f86b2f8cd93579dabc8643 / position / sync / chooseOneResults.js

1789 bytesRaw
1var getMsgContent = require('../../lib/getMsgContent')
2var ChooseOne = require('../../poll/sync/chooseOne')
3const PositionChoiceError = require('../../errors/sync/positionChoiceError')
4const 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.
17module.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
51function deleteExistingVotesByAuthor ({author, results}) {
52 results.forEach(result => {
53 if (result.voters[author]) {
54 delete result.voters[author]
55 }
56 })
57}
58
59function isInvalidChoice ({position, poll}) {
60 const { choice } = position.value.content.details
61 return choice >= poll.value.content.details.choices.length
62}
63
64function isPositionLate ({position, poll}) {
65 return position.value.timestamp > poll.value.content.closesAt
66}
67

Built with git-ssb-web