UNPKG

condorcet-winner

Version:

A simple condorcet vote algorithm implementation in typescript

32 lines (31 loc) 1.02 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.condorcetWinner = condorcetWinner; function condorcetWinner(candidates, ballots) { const votes = candidates.reduce((votes, candidate) => { votes[candidate] = 0; return votes; }, {}); ballots.forEach((ballot) => { ballot.forEach((candidate, index) => { votes[candidate] += ballot.length - index; }); }); const sortedCandidates = candidates.sort((a, b) => votes[b] - votes[a]); for (let i = 0; i < sortedCandidates.length; i++) { const candidate = sortedCandidates[i]; let hasBeenBeaten = false; for (let j = 0; j < sortedCandidates.length; j++) { if (i === j) continue; if (votes[candidate] <= votes[sortedCandidates[j]]) { hasBeenBeaten = true; break; } } if (!hasBeenBeaten) { return candidate; } } return null; }