Eu ainda não assisti a resolução da aula mas o meu código ficou assim
/Primeiro precisamos fazer a função adicionar, onde adicionamos os nomes a uma lista
//Botão reiniciar que reseta tudo ao ser clicado
let listaDeNomes = []
function adicionar(){
let nomeDeAmigo = document.getElementById("nome-amigo").value;
if (nomeDeAmigo == "") {
alert("Digite um nome antes de adicionar.");
return;
}
listaDeNomes.push(nomeDeAmigo);
document.getElementById("lista-amigos").textContent = listaDeNomes.join(", ");
document.getElementById("nome-amigo").value = "";
}
// Busquei na documentação como embaralhar uma lista
function embaralhar(array) {
let indiceAtual = array.length;
while (indiceAtual !== 0) {
let indiceAleatorio = Math.floor(Math.random() * indiceAtual);
indiceAtual--;
// Troca o elemento atual com o elemento aleatório
[array[indiceAtual], array[indiceAleatorio]] = [
array[indiceAleatorio], array[indiceAtual]
];
}
return array;
}
//Segundo passo é a função sortear juntando cada nome da lista com outro nome de forma aleatória porém sem repetir
function sortear(){
if (listaDeNomes.length < 2) {
alert("Adicione pelo menos 2 participantes para realizar o sorteio.");
return;
}
let listaSorteada = [...listaDeNomes];
do {
embaralhar(listaSorteada);
} while (
listaDeNomes.some((nome, indice) => nome === listaSorteada[indice])
);
document.getElementById("lista-sorteio").innerHTML = "";
for (let i = 0; i < listaDeNomes.length; i++) {
document.getElementById("lista-sorteio").innerHTML +=
`${listaDeNomes[i]} tirou ${listaSorteada[i]}<br>`;
}
}
//Criar a função reiniciar para zerar todos os campos
function reiniciar() {
document.getElementById("nome-amigo").value = "";
listaDeNomes = []
document.getElementById("lista-amigos").textContent = "";
document.getElementById("lista-sorteio").innerHTML = ""
}