Skip to content

Instantly share code, notes, and snippets.

@rodriguesabner
Last active December 13, 2022 13:37
Show Gist options
  • Save rodriguesabner/3b3a73445c0418f9fab2a59ad1567d7b to your computer and use it in GitHub Desktop.
Save rodriguesabner/3b3a73445c0418f9fab2a59ad1567d7b to your computer and use it in GitHub Desktop.
Amigo Secreto - Exemplo Final
import participants from "./participants.json"
import nodemailer from "nodemailer"
interface ParticipantProps {
name: string;
email: string;
not?: string[];
}
interface ParticipantsSortedProps extends ParticipantProps {
chosen: ParticipantProps;
}
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(): ParticipantsSortedProps[] {
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;
}
async sendMail(participants: ParticipantsSortedProps[]) {
let transporter = nodemailer.createTransport({
host: "HOST",
port: 465,
secure: true,
auth: {
user: "EMAIL",
pass: "SENHA",
},
});
const tasks = [];
for (const participant of participants) {
tasks.push(transporter.sendMail({
from: '"Amigo Secreto 👀"',
to: participant.email,
subject: "Amigo Secreto - Você tirou...",
text: `Olá ${participant.name}! Você tirou o(a) participante ${participant.chosen.name}`,
}));
}
await Promise.all(tasks)
return true;
}
}
const amigoSecreto = new AmigoSecreto()
const sortedParticipants = amigoSecreto.sortParticipants()
amigoSecreto.sendMail(sortedParticipants)
.then(() => console.log("Emails enviados com sucesso!"))
.catch((err) => console.log(err))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment