The draw algorithm is the core of the Amigo Invisible service. It is implemented inDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/Sufianeh7/AmigoInvisible/llms.txt
Use this file to discover all available pages before exploring further.
Node/utils/algoritmoSorteo.js and exposed as the generarEmparejamientos function. The lanzarSorteo controller calls it after verifying that the group exists and has enough participants. The algorithm’s approach is straightforward: randomly shuffle the participant list, validate every resulting pair against two rules, and retry up to 1,000 times until a fully valid assignment is found.
How It Works
Shuffle the participants array
The helper function
mezclarArray creates a copy of the participants array and applies a Fisher-Yates shuffle — iterating from the last element backwards and swapping each element with a randomly chosen element at or before its position. The original participantes array is never mutated.Assign givers to receivers by index
After shuffling, the algorithm pairs participants positionally: the participant at index
i in the original array is the giver, and the participant at index i in the shuffled array is the receiver. Because both arrays have the same length, every participant is both a giver and a receiver exactly once.Validate each pair against two rules
For every
(giver, receiver) pair the algorithm checks:- Rule 1 — No self-gifting:
giver.email !== receiver.email - Rule 2 — Respect exclusions:
receiver.nombremust not appear ingiver.exclusiones
breaks early).Retry on failure
When a shuffle produces at least one invalid pair, the outer
for loop increments the attempt counter and calls mezclarArray again to generate a fresh shuffle. No partial results are kept between attempts.Return valid pairings
If all
participantes.length pairs pass both rules, the algorithm returns an array of { de: email, para: email } objects — one entry per giver-receiver pair. This array is then saved to the database and passed to the mailer.Full Source
Constraints
The following rules govern what constitutes a valid draw. Some are enforced insidegenerarEmparejamientos itself; others are enforced by the controller before the utility is called.
| Constraint | Enforced by |
|---|---|
| Minimum 3 participants required | lanzarSorteo controller (returns 404 if fewer than 3) |
| Self-gifting is always forbidden | algoritmoSorteo.js — Rule 1 |
| Exclusions are one-directional | algoritmoSorteo.js — Rule 2 |
exclusiones list, Alice will never be assigned Bob as her recipient. However, Bob may still draw Alice’s name — exclusions only constrain the giver, not the receiver.
Error Handling
If the algorithm cannot find a valid complete assignment within 1,000 attempts, it throws:lanzarSorteo controller catches this with a try/catch block and forwards error.message to the client as a 400 Bad Request response: