Line data Source code
1 : import { Engine } from "../types.ts"; 2 1 : import { sliceArray } from "../utils/sliceArray.ts"; 3 1 : import { shuffle } from "./shuffle.ts"; 4 : 5 : /** 6 : * From the population array, produce an array with sampleSize elements that 7 : * are randomly chosen without repeats. 8 : * @param engine The Engine to use when choosing random values 9 : * @param population An array that has items to choose a sample from 10 : * @param sampleSize The size of the result array 11 : */ 12 0 : export function sample<T>( 13 0 : engine: Engine, 14 0 : population: ArrayLike<T>, 15 0 : sampleSize: number 16 : ): T[] { 17 0 : if ( 18 0 : sampleSize < 0 || 19 0 : sampleSize > population.length || 20 0 : !isFinite(sampleSize) 21 0 : ) { 22 0 : throw new RangeError( 23 0 : "Expected sampleSize to be within 0 and the length of the population" 24 0 : ); 25 0 : } 26 : 27 0 : if (sampleSize === 0) { 28 0 : return []; 29 0 : } 30 : 31 0 : const clone = sliceArray.call(population); 32 0 : const length = clone.length; 33 0 : if (length === sampleSize) { 34 0 : return shuffle(engine, clone, 0); 35 0 : } 36 0 : const tailLength = length - sampleSize; 37 0 : return shuffle(engine, clone, tailLength - 1).slice(tailLength); 38 0 : }