Line data Source code
1 : import { Engine } from "../types.ts"; 2 1 : import { integer } from "./integer.ts"; 3 : 4 : /** 5 : * Shuffles an array in-place 6 : * @param engine The Engine to use when choosing random values 7 : * @param array The array to shuffle 8 : * @param downTo minimum index to shuffle. Only used internally. 9 : */ 10 0 : export function shuffle<T>( 11 0 : engine: Engine, 12 0 : array: T[], 13 0 : downTo: number = 0 14 : ): T[] { 15 0 : const length = array.length; 16 0 : if (length) { 17 0 : for (let i = (length - 1) >>> 0; i > downTo; --i) { 18 0 : const distribution = integer(0, i); 19 0 : const j = distribution(engine); 20 0 : if (i !== j) { 21 0 : const tmp = array[i]; 22 0 : array[i] = array[j]; 23 0 : array[j] = tmp; 24 0 : } 25 0 : } 26 0 : } 27 0 : return array; 28 0 : }