Capítulo 186 de 411
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.
weightedRandom(collection, ease) returns a reusable function; each call returns a weighted-random element from collection.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.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
gsap.utils functions with pipe() to build a custom random distribution."power4" weights heavily toward one end, "none" is uniform.