Skip to content

Instantly share code, notes, and snippets.

@nickx720
Created October 21, 2021 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickx720/b137081569c0a649c9bf4a724d4b77dd to your computer and use it in GitHub Desktop.
Save nickx720/b137081569c0a649c9bf4a724d4b77dd to your computer and use it in GitHub Desktop.
Nylas Secret Santa

Tested on Node v.15.14.0

To run script

node index.js
const getRandomIndex = (start,end) => {
return Math.trunc(Math.random() * (end-start) + start);
}
const giftExchange = (arr)=>{
let length = arr.length;
if (length <= 2) {
throw new Error("Insufficient friends");
}
let map = new Map();
while ([...map.entries()].length < length) {
let gifter = arr.shift();
let index = getRandomIndex(0,arr.length-1);
if ([...map.values()].includes(arr[index]) || map.get(arr[index]) === gifter){
arr.push(gifter);
continue;
}
map.set(gifter,arr[index]);
arr.push(gifter);
}
let output= "";
for (const [gifter,receiver] of map.entries()){
output+= `${gifter} gives a gift to ${receiver}\n`;
}
return output;
}
const run = () => {
console.log(giftExchange(["Susan","Beth","Abe","Ardi", "Quan"]));
console.log(giftExchange(["Susan","Beth","Abe","Ardi", "Quan","Nick","Tom","Hamsa","Helen"]));
console.log(giftExchange(["Susan","Beth"]));
}
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment