-
Notifications
You must be signed in to change notification settings - Fork 1
/
select-santa.js
56 lines (45 loc) · 1.42 KB
/
select-santa.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
var secretSanta = function(people) {
this.people = people;
this.redo = false;
}
secretSanta.prototype.randomIntGenerator = function(limit) {
return Math.floor(Math.random()*(limit))
}
secretSanta.prototype.pickSanta = function(child, santasLeft) {
var len = santasLeft.length
var chosen_santa = santasLeft[this.randomIntGenerator(len)]
while (chosen_santa === child) {
// if the last person gets themselves, stop the process and catch it later
if (santasLeft.length === 1) {
this.redo = true;
break;
}
else {
chosen_santa = santasLeft[this.randomIntGenerator(len)];
}
};
return chosen_santa
}
secretSanta.prototype.draw = function(children, santasLeft) {
childToSanta = []
this.redo = false
for (i = 0; i < children.length; i++) {
santa = this.pickSanta(children[i], santasLeft)
childToSanta[children[i]] = santa
console.log("Children to Santa: ", childToSanta);
santasLeft.splice(santasLeft.indexOf(santa), 1)
};
return childToSanta
}
secretSanta.prototype.validDraw = function () {
var santas = Array();
for (p in this.people) santas.push(this.people[p]);
var children = Array();
for (p in this.people) children.push(this.people[p]);
var attemptToDraw = this.draw(children, santas);
if(this.redo) {
return this.validDraw();
}
return attemptToDraw;
};
module.exports = secretSanta;