Skip to content

Instantly share code, notes, and snippets.

@rodriguesabner
Created December 13, 2022 13:10
Show Gist options
  • Save rodriguesabner/43dba765aff4931ed2c0ac1b1abd7f50 to your computer and use it in GitHub Desktop.
Save rodriguesabner/43dba765aff4931ed2c0ac1b1abd7f50 to your computer and use it in GitHub Desktop.
Amigo Secreto
import participants from "./participants.json"
interface ParticipantProps {
name: string;
email: string;
not?: string[];
}
class AmigoSecreto {
shuffle(array: ParticipantProps[]): ParticipantProps[] {
let currentIndex: number = array.length
let temporaryValue;
let randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
sortParticipants(){
if(participants.length < 3){
throw new Error("Número de participantes insuficiente")
}
let shuffledParticipants = [];
do {
const shuffled = this.shuffle(participants.map((item) => ({email: item.email, name: item.name})))
shuffledParticipants = participants.map((p, i) => ({
...p,
chosen: {email: shuffled[i].email, name: shuffled[i].name}
}))
} while (shuffledParticipants.some(person => {
const chosenHimself = person.email === person.chosen.email
const notAllowed = person.not != null && person.not.some(n => n === person.chosen.name)
return (chosenHimself || notAllowed)
}))
return shuffledParticipants;
}
}
const teste = new AmigoSecreto().sortParticipants();
console.log(teste);
[
{
"name": "User 1",
"email": "[email protected]",
"not": ["User 3"]
},
{
"name": "User 2",
"email": "[email protected]",
"not": []
},
{
"name": "User 3",
"email": "[email protected]",
"not": []
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment