Here’s a script for your family’s secret Santa

‘’’

const names = []

function createSecretSanta(names) {

if (names.length < 2) {

throw new Error("Need at least 2 names for Secret Santa")

}

const shuffled = [...names]

for (let i = shuffled.length - 1; i > 0; i--) {

const j = Math.floor(Math.random() * (i + 1));

[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]

}

const assignments = []

for (let i = 0; i < shuffled.length; i++) {

const giver = shuffled[i]

const receiver = shuffled[(i + 1) % shuffled.length]

assignments.push({ giver, receiver })

}

return assignments

}

const assignments = createSecretSanta(names)

assignments.forEach((assignment) => {

console.log(`${assignment.giver} -> ${assignment.receiver}`)

})

‘’’

Reply to this note

Please Login to reply.

Discussion

No replies yet.