DEV Community

Walter Nascimento
Walter Nascimento

Posted on

Sortition Names with JS

Using JavaScript, let's create a Sortition Names with JS

Code

HTML

<fieldset>
  <legend>Resultado</legend>
  <div>
    <label for="inputIniEl">
      Informe os itens a serem embaralhados, separados por <strong>quebra de linha</strong> ou <strong>ponto e
      vírgula</strong>.
    </label> <br>
    <textarea name="inputIniEl" id="inputIniEl" cols="30" rows="10"></textarea>
  </div>
  <span>Ou informe o arquivo <strong>.txt</strong></span>
  <div>
    <input type="file" id="file">
  </div>
  <div>
    Exibir apenas os primeiros <input type="number" id="inputEl"> itens embaralhados.
  </div>
  <button id="play">Sorteio</button>
</fieldset>


<fieldset id="result" style="display: none;">
  <legend>Resultado</legend>
  <table>
    <thead>
      <th>Ordem</th>
      <th>Nome</th>
    </thead>
    <tbody id="output"></tbody>
  </table>
  <div>Sorteio realizado em: <strong id="date"></strong> às <strong id="time"></strong></div>
</fieldset>
Enter fullscreen mode Exit fullscreen mode

This code is for an HTML form that allows a user to input a list of items, either by typing them into a text area or by uploading a .txt file. The user can also specify how many items from the shuffled list they want to see. There is a "Sorteio" button that when clicked, will shuffle the items and display them in a table with "Ordem" (order) and "Nome" (name) columns. The form also includes a "Resultado" (result) fieldset that will be hidden until the "Sorteio" button is clicked. The fieldset will also display the date and time of the sorteio.

JS

const playEl = document.querySelector('#play');
const outputEl = document.querySelector('#output');
const dateEl = document.querySelector('#date');
const timeEl = document.querySelector('#time');
const resultEl = document.querySelector('#result');
const inputEl = document.querySelector('#inputEl');
const inputIniEl = document.querySelector('#inputIniEl');
const fileEl = document.querySelector('#file');

playEl.addEventListener('click', main);

function getRandom(min = 0, max = 2) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

function readFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();

    reader.onload = res => {
      resolve(res.target.result);
    };
    reader.onerror = err => reject(err);

    reader.readAsText(file);
  });
}

async function onSubmit() {
  let file = fileEl.files[0];
  console.log(await readFile(file));
}

function dateNow(input = Date.now()) {
  let date = new Date(input);
  let localeDate = date.toLocaleDateString('pt-BR', { dateStyle: 'long' });
  let localeTime = date.toLocaleTimeString('pt-BR', { timeStyle: "medium" });
  return { localeDate, localeTime };
}

function generateTable(table, data) {
  for (let [key, value] of data.entries()) {
    let row = table.insertRow();
    let cell = row.insertCell();
    let text = document.createTextNode(`${key + 1}°`);
    cell.appendChild(text);

    cell = row.insertCell();
    text = document.createTextNode(`${value}`);
    cell.appendChild(text);
  }
}

async function main() {
  resultEl.style.display = "none";
  let loop = inputEl.value;
  let data = [];
  let file = fileEl.files[0];
  if (!file) {
    data = inputIniEl.value.split(/[\n|;]+/);
  } else {
    data = (await readFile(file)).trim().split(/[\n|;]+/);
  }
  let result = [];

  while (loop) {
    let random = getRandom(0, data.length);
    if (!result.includes(data[random])) {
      result.push(data[random]);
      loop--;
    }
  }
  console.log(result);

  outputEl.innerHTML = "";
  generateTable(outputEl, result);

  let { localeDate, localeTime } = dateNow();
  dateEl.innerHTML = localeDate;
  timeEl.innerHTML = localeTime;
  resultEl.style.display = "block";
}
Enter fullscreen mode Exit fullscreen mode

This code is a JavaScript script that creates a simple randomizer application. It uses the DOM (Document Object Model) to access and manipulate the elements of an HTML page.

When the button with the id "play" is clicked, the main function is executed. This function starts by hiding the "result" fieldset, then it initializes some variables.

It checks if a file has been selected, if not, it takes the input from the textarea with the id "inputIniEl" and splits it by newline or semicolon. If a file is selected, it reads the contents of the file and splits it the same way.

Then the code uses a while loop to generate a random number between 0 and the length of the data array, and if the value generated isn't already in the result array, it adds it and continues looping until the inputEl.value is reached.

Then it clears the output table, generates a new table with the result array and populates it, and shows the "result" fieldset.

It also calls the dateNow function to get the current date and time and shows it in the output.

The getRandom function generates a random number between min and max, the readFile function reads the contents of a file and returns the contents as a string, the dateNow function returns the current date and time in a specific format, and the generateTable function generates a table with the data passed to it.

Demo

See below for the complete working project.

💡 NOTE: If you can't see it click here and see the final result


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you later! 😊😊


Support Me

Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso

Top comments (0)