Find top votes
by Matthew Vasallo
JavaScript
const votes = ["Matt", "Christine", "Dawn", "Pedro", "Mark", "Matthew", "Gaby", "Matt", "Mark", "Gaby", "Matt", "Pedro", "Matthew", "Matthew"];
const findWinner = votes => {
const voteCountLookup = {};
let leadingVotes = [];
let currentHeighestVote = 0;
votes.forEach(vote => {
let count = voteCountLookup[vote];
(count > 0) ? count++ : count = 1;
voteCountLookup[vote] = count;
if (count > currentHeighestVote) {
currentHeighestVote = count;
leadingVotes = [vote];
} else if (count === currentHeighestVote) {
//Tie
leadingVotes.push(vote);
}
});
console.log(voteCountLookup);
console.log(leadingVotes);
return leadingVotes;
};
const compareWinnersAtPos = (winners, pos) => {
let newWinners = [];
let currentMaxLetterValue = 0;
winners.forEach(name => {
if (name.charCodeAt(pos) > currentMaxLetterValue) {
currentMaxLetterValue = name.charCodeAt(pos);
newWinners = [name];
} else if (name.charCodeAt(pos) === currentMaxLetterValue) {
newWinners.push(name);
}
});
return newWinners;
};
const breakTie = winners => {
let currentLetterPos = 0;
while (winners.length > 1) {
winners = compareWinnersAtPos(winners, currentLetterPos);
currentLetterPos++;
}
return winners[0];
};
let winner = breakTie(findWinner(votes));
console.log("winner is ", winner);