Skip to content

Commit

Permalink
fixup! fix: use method of largest remainder to count poll votes
Browse files Browse the repository at this point in the history
Signed-off-by: Maksim Sukharev <antreesy.web@gmail.com>
  • Loading branch information
Antreesy committed Oct 28, 2024
1 parent 98def9b commit b522bb6
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions src/utils/calculateVotePercentage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

type VoteAccumulator = { rounded: number[], wholes: number[], remainders: number[] }

/**
* Finds indexes of largest remainders to distribute quota
* @param array array of numbers to compare
Expand Down Expand Up @@ -36,21 +34,28 @@ export function calculateVotePercentage(votes: number[], total: number) {
return votes
}

const { rounded, wholes, remainders } = votes.reduce((acc: VoteAccumulator, vote, idx) => {
const quota = vote / total * 100
acc.rounded[idx] = Math.round(quota)
acc.wholes[idx] = Math.floor(quota)
acc.remainders[idx] = Math.round((quota - Math.floor(quota)) * 1000)
return acc
}, { rounded: [], wholes: [], remainders: [] })
const rounded: number[] = []
const wholes: number[] = []
const remainders: number[] = []
let sumRounded = 0
let sumWholes = 0

for (const i in votes) {
const quota = votes[i] / total * 100
rounded.push(Math.round(quota))
wholes.push(Math.floor(quota))
remainders.push(Math.round((quota % 1) * 1000))
sumRounded += rounded[i]
sumWholes += wholes[i]
}

// Check if simple round gives 100%
if (rounded.reduce((acc, value) => acc + value) === 100) {
if (sumRounded === 100) {
return rounded
}

// Increase values by largest remainder method if difference allows
for (let i = 100 - wholes.reduce((acc, value) => acc + value); i > 0;) {
for (let i = 100 - sumWholes; i > 0;) {
const largest = getLargestIndexes(remainders)
if (largest.length > i) {
return wholes
Expand Down

0 comments on commit b522bb6

Please sign in to comment.