Build a Voting System - Build a Voting System

Tell us what’s happening:

I DONT UNDERSTAND WHY MY CODE IS NOT PASSING. I HAVE CREATED A POLL VARIABLE & the rest of the code

Your code so far

// ============================================================
//  VOTING SYSTEM - Core Logic
//  Uses Map (poll) and Set (voters per option)
// ============================================================

const poll = new Map();

function addOption(option) {
  if (!option || option.trim() === "") {
    return "Option cannot be empty";
  }
  option = option.trim();
  if (poll.has(option)) {
    return `Option "${option}" already exists`;
  }
  poll.set(option, new Set());
  return `Option "${option}" added to the poll`;
}

function vote(option, voterId) {
  if (!poll.has(option)) {
    return `Option "${option}" does not exist`;
  }
  const voters = poll.get(option);
  if (voters.has(voterId)) {
    return `Voter ${voterId} has already voted for "${option}"`;
  }
  voters.add(voterId);
  return `Voter ${voterId} voted for "${option}"`;
}

function displayResults() {
  if (poll.size === 0) {
    return "Poll Results:\n(No options yet)";
  }
  let result = "Poll Results:\n";
  poll.forEach((voters, option) => {
    result += `${option}: ${voters.size} votes\n`;
  });
  return result.trimEnd();
}

// Seed: at least 3 options and 3 votes
addOption("Turkey");
addOption("Morocco");
addOption("Spain");

vote("Turkey", "traveler1");
vote("Turkey", "traveler2");
vote("Morocco", "traveler3");

// ============================================================
//  VOTING SYSTEM - UI Layer
//  Depends on poll, addOption, vote, displayResults from script.js
// ============================================================

function classify(message) {
  if (
    message.includes("added to the poll") ||
    (message.includes("voted for") && !message.includes("already"))
  ) {
    return "success";
  }
  if (
    message.includes("already exists") ||
    message.includes("already voted") ||
    message.includes("does not exist") ||
    message.includes("cannot be empty")
  ) {
    return "error";
  }
  return "info";
}

function addLog(message) {
  const list = document.getElementById("log-list");
  const type = classify(message);
  const li = document.createElement("li");
  li.className = `log-item ${type}`;
  li.textContent = message;
  list.insertBefore(li, list.firstChild);
}

function renderOptions() {
  const grid = document.getElementById("options-grid");
  grid.innerHTML = "";

  if (poll.size === 0) {
    grid.innerHTML = '<p class="empty-state">No options added yet.</p>';
    return;
  }

  const maxVotes = Math.max(...[...poll.values()].map((s) => s.size), 1);

  poll.forEach((voters, option) => {
    const pct = Math.round((voters.size / maxVotes) * 100);
    const card = document.createElement("div");
    card.className = "option-card";
    card.innerHTML = `
      <div class="option-name">${option}</div>
      <div class="option-votes">${voters.size} vote${voters.size !== 1 ? "s" : ""}</div>
      <div class="vote-bar-wrap">
        <div class="vote-bar" style="width: ${pct}%"></div>
      </div>
    `;
    grid.appendChild(card);
  });
}

function showResults() {
  const box = document.getElementById("results-box");
  const text = displayResults();
  box.textContent = text;
  box.classList.remove("empty");
}

function setMessage(id, text, type) {
  const el = document.getElementById(id);
  el.textContent = text;
  el.className = `message-box ${type}`;
}

// ---- Add Option Handler ----
document.getElementById("btn-add-option").addEventListener("click", () => {
  const input = document.getElementById("input-option");
  const raw = input.value.trim();
  const msg = addOption(raw);
  const type = classify(msg);
  setMessage("msg-add", msg, type);
  addLog(msg);
  if (type === "success") {
    input.value = "";
    renderOptions();
    showResults();
  }
});

document.getElementById("input-option").addEventListener("keydown", (e) => {
  if (e.key === "Enter") document.getElementById("btn-add-option").click();
});

// ---- Vote Handler ----
document.getElementById("btn-vote").addEventListener("click", () => {
  const optInput = document.getElementById("input-vote-option");
  const idInput = document.getElementById("input-voter-id");
  const option = optInput.value.trim();
  const voterId = idInput.value.trim();

  if (!option || !voterId) {
    setMessage(
      "msg-vote",
      "Please enter both an option and a voter ID.",
      "error",
    );
    return;
  }

  const msg = vote(option, voterId);
  const type = classify(msg);
  setMessage("msg-vote", msg, type);
  addLog(msg);
  if (type === "success") {
    optInput.value = "";
    idInput.value = "";
    renderOptions();
    showResults();
  }
});

document.getElementById("input-voter-id").addEventListener("keydown", (e) => {
  if (e.key === "Enter") document.getElementById("btn-vote").click();
});

// ---- Display Results Handler ----
document.getElementById("btn-results").addEventListener("click", () => {
  showResults();
});

// ---- Initial Render ----
renderOptions();
showResults();

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36 Edg/146.0.0.0

Challenge Information:

Build a Voting System - Build a Voting System

Hey there,

Please update the message to include your code. The code was too long to be automatically inserted by the help button.

When you enter a code, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

Welcome back @QMS85!

I’m seeing this error in the console:

ReferenceError: document is not defined

Edit:

Please check each one of the messages you are returning to make sure they match the instructions exactly.

Also, you were not asked to build a UI layer.

Happy coding!

1 Like

Thanks for your feedback @dhess i’ll check my code again.