Last active
November 10, 2021 13:16
-
-
Save n8jadams/ded8f47a0148de5e0c60754f2d3ab303 to your computer and use it in GitHub Desktop.
A quick typescript function to assign siblings in our yearly gift exchange
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Participant { | |
readonly name: string | |
assignment?: Participant | |
} | |
const allParticipants: Participant[] = [ | |
{ name: 'Nate' }, | |
{ name: 'Kyle' }, | |
{ name: 'Zach' }, | |
{ name: 'Bryce' }, | |
{ name: 'Sofia' }, | |
{ name: 'Kiersten' }, | |
{ name: 'Emily' } | |
] | |
function getRandomIntInclusive(x: number, y: number): number { | |
const min = Math.min(x, y) | |
const max = Math.max(x, y) | |
return Math.floor(Math.random() * (max - min + 1) + min) | |
} | |
function assignParticipants(group: Participant[]): Participant[] { | |
const participants = [...group] | |
const alreadyAssignedList: Participant[] = [] | |
participants.forEach((gifter) => { | |
const potentialGifters = participants.filter((p) => { | |
const personIsAssignedToGifter = p.assignment && p.assignment.name === gifter.name | |
const personIsAssignedToAnother = alreadyAssignedList.some((aap) => aap.name === p.name) | |
const personIsGifter = p.name !== gifter.name | |
if(personIsAssignedToGifter || personIsAssignedToAnother) { | |
return false | |
} | |
return personIsGifter | |
}) | |
const randomGifterIndex = getRandomIntInclusive(0, potentialGifters.length - 1) | |
gifter.assignment = potentialGifters[randomGifterIndex] | |
alreadyAssignedList.push(gifter.assignment) | |
}) | |
return participants | |
} | |
function outputAssignedResults(group: Participant[]): void { | |
group.forEach((p) => { | |
if(p?.name && p?.assignment?.name) { | |
console.log(`${p.name} will give a gift to ${p.assignment.name}`) | |
} | |
}) | |
} | |
const assignedParticipants = assignParticipants(allParticipants) | |
outputAssignedResults(assignedParticipants) | |
// Results: | |
// Nate will give a gift to Kyle | |
// Kyle will give a gift to Emily | |
// Zach will give a gift to Nate | |
// Bryce will give a gift to Sofia | |
// Sofia will give a gift to Zach | |
// Kiersten will give a gift to Bryce | |
// Emily will give a gift to Kiersten |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment