Capítulo 186 de 411

Chapter 186: Weighted Random Pick From an Array (Helper)

Core Idea

A helper that picks a random element from an array biased toward one end, by piping Math.random() through an ease before mapping it to an array index — unlike plain Math.random() * length, which is uniform.

Key Concepts

  • weightedRandom(collection, ease) returns a reusable function; each call returns a weighted-random element from collection.
  • Chains gsap.utils.pipe(): random 0-1 → apply the ease → gsap.utils.mapRange() to the index range (stretched ±0.5 for even rounding distribution) → gsap.utils.snap(1) to the nearest integer → index into the array.

Code Examples

function weightedRandom(collection, ease) {
  return gsap.utils.pipe(
    Math.random,
    gsap.parseEase(ease),
    gsap.utils.mapRange(0, 1, -0.5, collection.length - 0.5),
    gsap.utils.snap(1),
    (i) => collection[i]
  );
}

let getRandom = weightedRandom([0, 1, 2, 3], "power4");
getRandom(); // weighted toward the end of the array
  • What it demonstrates: composing several gsap.utils functions with pipe() to build a custom random distribution.

Key Takeaways

  1. The ease's shape controls the bias — e.g. "power4" weights heavily toward one end, "none" is uniform.

Connects To

  • gsap.utils.pipe(), gsap.utils.mapRange(), gsap.utils.snap(): the utility building blocks composed here.