Created
December 13, 2022 13:10
-
-
Save rodriguesabner/43dba765aff4931ed2c0ac1b1abd7f50 to your computer and use it in GitHub Desktop.
Amigo Secreto
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"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