Skip to content

Instantly share code, notes, and snippets.

@marcmartino
Created July 7, 2018 00:36
Show Gist options
  • Select an option

  • Save marcmartino/c46d63f0bec0d84e23632892473a8732 to your computer and use it in GitHub Desktop.

Select an option

Save marcmartino/c46d63f0bec0d84e23632892473a8732 to your computer and use it in GitHub Desktop.
function randomSelection<T>(numToSelect: number, list: T[]): T[] {
return take(numToSelect, randomizeList(range(0, list.length)))
.map((i) => list[i]);
}
function randomizeList<T>(xs: T[], randomized: T[] = []): T[] {
if (xs.length) {
const {arr, val} = slice(Math.floor(Math.random() * xs.length), xs);
return randomizeList(arr, randomized.concat([val]));
}
return randomized;
}
function slice<T>(pos: number, xs: T[]): {arr: T[], val: T} {
return ({ val: xs[pos], arr: xs.slice(0, pos).concat(xs.slice(pos+1))});
}
function take<T>(num: number, xs: T[]): T[] {
return num === 1 ? head(xs) : [head(xs)].concat(take(num - 1, tail(xs)))
}
function head<T>(xs: T[]): T {
return xs[0];
}
function tail<T>(xs: T[]): T[] {
return xs.slice(1);
}
function range(start: number, end: number): number[] {
return Array.from(new Array(end - start), (_, i) => i + start);
}
console.log(randomSelection(3, [1,2,3,4,5,6,7,8,9,10]))
console.log(randomSelection(2, ['john', 'jazz', 'stan', 'ethan']));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment