Skip to content

Instantly share code, notes, and snippets.

@nilscox
Created December 2, 2022 15:28
Show Gist options
  • Select an option

  • Save nilscox/9e7f743dca477b6bc58c82fb1c692384 to your computer and use it in GitHub Desktop.

Select an option

Save nilscox/9e7f743dca477b6bc58c82fb1c692384 to your computer and use it in GitHub Desktop.
const randomInteger = (max: number) => {
return Math.floor(Math.random() * max);
};
const secretSanta = (people: string[]): Array<[string, string]> => {
const result: Array<[string, string]> = [];
const available = people.slice(1);
let person1 = people[0];
while (available.length > 0) {
const index = randomInteger(available.length);
const person2 = available[index];
result.push([person1, person2]);
person1 = person2;
available.splice(index, 1);
}
result.push([person1, people[0]]);
return result;
};
describe('secret santa distribution', () => {
const count = 10;
it('secretSanta', () => {
const people = Array(count)
.fill(null)
.map((_, index) => `person${String(index).padStart(4, '0')}`);
const result = secretSanta(people);
expect(result.map(([person1]) => person1).sort()).toEqual(people);
expect(result.map(([, person2]) => person2).sort()).toEqual(people);
for (const [person1, person2] of result) {
expect(person1).not.toBe(person2);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment