Capítulo 177 de 411

Chapter 177: Pluck Random Values Without Repeats (Helper)

Core Idea

Two small helpers for picking random array elements: one that pulls every element exactly once before the pool "refills" and reshuffles, and one that just avoids repeating the immediately previous pick.

Key Concepts

  • pluckRandomFrom(array): shuffles a working copy (array.eligible, via gsap.utils.shuffle) and pops from it each call; once empty, reshuffles automatically. Guarantees every element is used before any repeats.
  • getRandomFrom(array): simpler — just rejects picks equal to array.selected (the previous pick), so only immediate repeats are avoided, not full-cycle uniqueness.

Code Examples

function pluckRandomFrom(array) {
  return (
    array.eligible && array.eligible.length
      ? array.eligible
      : (array.eligible = gsap.utils.shuffle(array.slice(0)))
  ).pop();
}
  • What it demonstrates: lazily building and draining a shuffled copy stored on the array itself, so no external state tracking is needed.

Key Takeaways

  1. Pick pluckRandomFrom when you need "every item shown once before repeats"; pick getRandomFrom when you only care about not repeating twice in a row.

Connects To

  • gsap.utils.shuffle(): the underlying randomization utility.