-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (59 loc) · 1.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const { sendEmail } = require("./sendgrid.js");
const data = require("./data.js");
require("dotenv").config();
function checkAssymetric(result, target) {
let existing;
result.forEach((user) => {
if (user.email === target) {
existing = user;
}
});
if (!existing) return true;
return existing.giftTo !== target;
}
function choose(data) {
const people = data.map(({ name, email }) => {
return { name, email };
});
const result = [];
let count = 0;
while (people.length > 0) {
const randomNumber = Math.floor(Math.random() * people.length);
const lastIndex = people.length - 1;
if (
people[lastIndex].email !== data[randomNumber].email &&
!data[randomNumber].exclude.includes(people[lastIndex].email)
) {
if (checkAssymetric(result, people[lastIndex].email)) {
data[randomNumber].giftTo = people[lastIndex].name;
result.push(data[randomNumber]);
people.pop();
data.splice(randomNumber, 1);
}
}
count++;
if (count > 50) {
return choose(data);
}
}
return result;
}
async function runSecretSanta() {
const result = choose(data);
console.log(result); //comment this
try {
await Promise.all(
result.map(async (participant) => {
await sendEmail({
to: participant.email,
giftTo: participant.giftTo,
});
})
);
console.log('Emails sent successfully');
} catch (e) {
console.error(e.response.body);
}
return;
}
runSecretSanta();