Sampling Utilities
Weighted Random API
Section titled “Weighted Random API”WeightedRandom
Section titled “WeightedRandom”Precomputed cumulative weights for efficient selection:
import { createWeightedRandom } from '@esengine/procgen';
const selector = createWeightedRandom([ { value: 'apple', weight: 5 }, { value: 'banana', weight: 3 }, { value: 'cherry', weight: 2 }]);
// Use with seeded randomconst result = selector.pick(rng);
// Use with Math.randomconst result2 = selector.pickRandom();
// Get probabilityconsole.log(selector.getProbability(0)); // 0.5 (5/10)console.log(selector.size); // 3console.log(selector.totalWeight); // 10Convenience Functions
Section titled “Convenience Functions”import { weightedPick, weightedPickFromMap } from '@esengine/procgen';
// Pick from arrayconst item = weightedPick([ { value: 'a', weight: 1 }, { value: 'b', weight: 2 }], rng);
// Pick from objectconst item2 = weightedPickFromMap({ 'common': 60, 'rare': 30, 'epic': 10}, rng);Shuffle API
Section titled “Shuffle API”shuffle / shuffleCopy
Section titled “shuffle / shuffleCopy”Fisher-Yates shuffle algorithm:
import { shuffle, shuffleCopy } from '@esengine/procgen';
const arr = [1, 2, 3, 4, 5];
// In-place shuffleshuffle(arr, rng);
// Create shuffled copy (original unchanged)const shuffled = shuffleCopy(arr, rng);pickOne
Section titled “pickOne”Randomly select one element:
import { pickOne } from '@esengine/procgen';
const items = ['a', 'b', 'c', 'd'];const item = pickOne(items, rng);Sampling API
Section titled “Sampling API”sample / sampleWithReplacement
Section titled “sample / sampleWithReplacement”import { sample, sampleWithReplacement } from '@esengine/procgen';
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Sample 3 unique elementsconst unique = sample(arr, 3, rng);
// Sample 5 (with possible repeats)const withRep = sampleWithReplacement(arr, 5, rng);randomIntegers
Section titled “randomIntegers”Generate random integer array within range:
import { randomIntegers } from '@esengine/procgen';
// 5 unique random integers from 1-100const nums = randomIntegers(1, 100, 5, rng);weightedSample
Section titled “weightedSample”Sample by weight (no replacement):
import { weightedSample } from '@esengine/procgen';
const items = ['A', 'B', 'C', 'D', 'E'];const weights = [10, 8, 6, 4, 2];
// Select 3 by weightconst selected = weightedSample(items, weights, 3, rng);Performance Tips
Section titled “Performance Tips”// Good: Create once, use many timesconst selector = createWeightedRandom(items);for (let i = 0; i < 1000; i++) { selector.pick(rng);}
// Bad: Create every timefor (let i = 0; i < 1000; i++) { weightedPick(items, rng);}