Skip to main content
πŸ“² JavaScript App Logic

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) β€” question is a string; options is an array of unique option strings.
  • vote(voterId, option) β€” cast a vote. Rules:
    • If option is not a valid option β†’ throw Error("Invalid option").
    • If voterId has already voted β†’ throw Error("Already voted").
    • Otherwise record the vote and return true.
  • getResults() β€” return an array of { option, votes } objects sorted by votes descending. Ties preserve original option order.
  • getWinner() β€” return the option string with the most votes. If no votes have been cast, return null. On a tie, return whichever tied option appears first in the original list.
  • totalVotes() β€” return the total number of votes cast.
  • hasVoted(voterId) β€” return true if 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.