git ssb

0+

Piet / ssb-loomio



Tree: 32a33a98ca920f7d44b96ee7b79cae654a047eee

Files: 32a33a98ca920f7d44b96ee7b79cae654a047eee / results / sync / buildResults.js

1985 bytesRaw
1const getContent = require('ssb-msg-content')
2const { isChooseOnePoll } = require('ssb-poll-schema')
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.
17
18// TODO find a better home for this (it is not strongly in poll nor position domain)
19module.exports = function ({positions, poll}) {
20 if (isChooseOnePoll(poll)) {
21 return chooseOneResults({positions, poll})
22 }
23}
24
25function chooseOneResults ({positions, poll}) {
26 var results = getContent(poll)
27 .details
28 .choices
29 .map(choice => {
30 return {
31 choice,
32 voters: {}
33 }
34 })
35
36 return positions.reduce(function (acc, position) {
37 const { author } = position.value
38 const { choice } = getContent(position).details
39
40 if (isInvalidChoice({position, poll})) {
41 acc.errors.push(PositionChoiceError({position}))
42 return acc
43 }
44
45 if (isPositionLate({position, poll})) {
46 acc.errors.push(PositionLateError({position}))
47 return acc
48 }
49
50 deleteExistingVotesByAuthor({results: acc.results, author})
51 acc.results[choice].voters[author] = position
52
53 return acc
54 }, {errors: [], results})
55}
56
57// !!! assumes these are already sorted by time.
58// modifies results passed in
59function deleteExistingVotesByAuthor ({author, results}) {
60 results.forEach(result => {
61 if (result.voters[author]) {
62 delete result.voters[author]
63 }
64 })
65}
66
67function isInvalidChoice ({position, poll}) {
68 const { choice } = position.value.content.details
69 return choice >= poll.value.content.details.choices.length
70}
71
72function isPositionLate ({position, poll}) {
73 return position.value.timestamp > poll.value.content.closesAt
74}
75

Built with git-ssb-web