What you're building
A Poll class that runs a multi-option vote β the kind of thing powering Slido, Mentimeter, or any live Q&A tool. You'll track who voted, prevent double-voting, and produce a ranked leaderboard.
Requirements
constructor(question, options)βquestionis a string;optionsis an array of unique option strings.vote(voterId, option)β cast a vote. Rules:- If
optionis not a valid option β throwError("Invalid option"). - If
voterIdhas already voted β throwError("Already voted"). - Otherwise record the vote and return
true.
- If
getResults()β return an array of{ option, votes }objects sorted byvotesdescending. Ties preserve original option order.getWinner()β return the option string with the most votes. If no votes have been cast, returnnull. On a tie, return whichever tied option appears first in the original list.totalVotes()β return the total number of votes cast.hasVoted(voterId)β returntrueif this voter has already voted.
Stretch goals
- Add
changeVote(voterId, newOption)that lets a voter switch their choice. - Add
reset()that clears all votes but keeps the question and options.
What this proves
You can enforce business constraints (unique voters, valid options), produce aggregated leaderboards, and handle tie-breaking β patterns that appear in auction systems, leaderboards, and any feature where you rank items by count.
β‘ 60 XP
solution.jsRuns in your browser
Loading editorβ¦
Tests4 to pass
vote records correctly and totalVotes reflects count
getWinner returns leading option
vote throws on invalid option and duplicate voter
getResults sorted descending with no votes returns zeros
Run your code to check these.