2021-10-18 Interview Poll

by Ttt Yyy

HTML

<div id='container'>
</div>

CSS

#container {
  border: 1px solid #ccc;
  padding: 10px;
}

.bar {
  border: 1px solid gray;
  background-color: #3b5998;
  color: black;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.row {
  display: flex;
}

.percent {
  padding: 0 5px;
}

.winner {
  color: blue;
}

.winner .bar {
  background-color: red;
}

.right {
  margin-left: 10px;
  flex: 1 1 auto;
}

JavaScript

const votes = [
  {
    label:
      "redredredredredredredredredredredredredredredredredredredredredredredredredredredred",
    count: 5,
  },
  { label: "blue", count: 20 },
  { label: "green", count: 10 },
];

function poll(votes, container) {
  let total = 0;
  let max = 0;

  // loop through votes to get total and max
  for (let { count } of votes) {
    total += count;
    max = Math.max(count, max);
  }

  // fragment to not cause too much reflow?
  let fragment = document.createDocumentFragment();
  for (let { count, label } of votes) {
    let row = document.createElement("div");
    row.className = "row";
    if (count === max) {
      row.className = "row winner";
    }
    const displayPercent = Math.round((count / total) * 100);
    const cssPercent = Math.round((count / max) * 100);
    row.innerHTML = `
      <div class='percent'>
        ${displayPercent}%
      </div>
      <div class='right' >
        <div class='bar' style='width: ${cssPercent}%'>${label}</div>
      </div>`;
    fragment.appendChild(row);
  }
  container.appendChild(fragment);
}

poll(votes, document.getElementById("container"));