Build a Voting System - Build a Voting System

Tell us what’s happening:

Last test is failing. Everything looks fine to me.
17. displayResults() should return the results in the correct format.

Your code so far

const poll = new Map();

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

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

addOption("Russia")
addOption("Spain")
addOption("Italy")
vote("Russia", "Alex")
vote("Russia", "Nicholas")
vote("Spain", "Andrew")
vote("Italy", "Kate")

function displayResults(poll) {
  let results = `Poll Results:`
  poll.forEach((value, key) => {
    results += `
${key}: ${value.size} votes`
  })
  return results
}

displayResults(poll)

Your browser information:

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

Challenge Information:

Build a Voting System - Build a Voting System

How does your function return the results and what is the correct format?

Looks pretty good to me. You could try using \n instead of a break in the literal like that, but I already tried it and it didn’t work.

You can use this to test:

addOption('Turkey');
  addOption('Morocco');

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

Output should be like this:

'Poll Results:\nTurkey: 2 votes\nMorocco: 1 votes'

If I modify it to use \n and then replace them all with \\n so I can see them, I get this output versus the expected:

Poll Results:\nTurkey: 2 votes\nMorocco: 1 votes
Poll Results:\nTurkey: 2 votes\nMorocco: 1 votes

I think this test is too strict…

This is what worked for me, although as far as I can tell it’s the exact same output.

The “Poll Results:” string needs to end with a newline \n.
The “votes” string needs to have a newline at the end.
you need to remove the last \n before returning the final string.

Created an issue for this here:
https://github.com/freeCodeCamp/freeCodeCamp/issues/60857

displayResults function is not expected to take any arguments.

1 Like

That does explain this error in the browser console:

TypeError: poll is undefined

It would be nice if this error showed in the FCC editor console, or if the test shared the result it’s receiving? Then we could see the test isn’t getting a result and investigate further based on that.

Otherwise the test response is very cryptic.