git ssb

0+

Piet / ssb-loomio



Tree: b792992e79b3b28771b347e53432ec76daa47ee5

Files: b792992e79b3b28771b347e53432ec76daa47ee5 / results / sync / buildResults.js

2043 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 console.log(position)
38 const { author } = position.value
39 const { choice } = getContent(position).details
40 console.log(author, choice)
41
42 if (isInvalidChoice({position, poll})) {
43 acc.errors.push(PositionChoiceError({position}))
44 return acc
45 }
46
47 if (isPositionLate({position, poll})) {
48 acc.errors.push(PositionLateError({position}))
49 return acc
50 }
51
52 deleteExistingVotesByAuthor({results: acc.results, author})
53 acc.results[choice].voters[author] = position
54
55 return acc
56 }, {errors: [], results})
57}
58
59// !!! assumes these are already sorted by time.
60// modifies results passed in
61function deleteExistingVotesByAuthor ({author, results}) {
62 results.forEach(result => {
63 if (result.voters[author]) {
64 delete result.voters[author]
65 }
66 })
67}
68
69function isInvalidChoice ({position, poll}) {
70 const { choice } = position.value.content.details
71 return choice >= poll.value.content.details.choices.length
72}
73
74function isPositionLate ({position, poll}) {
75 return position.value.timestamp > poll.value.content.closesAt
76}
77

Built with git-ssb-web