2020-06-26 09:31:23 +00:00
|
|
|
export function sampleSize(array: string[], n: number): string[] {
|
2021-11-09 07:02:59 +00:00
|
|
|
const length = array ? array.length : 0;
|
2020-06-26 09:31:23 +00:00
|
|
|
if (!length || n < 1) {
|
|
|
|
return [];
|
|
|
|
}
|
2021-11-08 19:20:03 +00:00
|
|
|
|
2021-11-09 06:04:34 +00:00
|
|
|
const sampleNumber = n > length ? length : n;
|
2020-06-26 09:31:23 +00:00
|
|
|
let index = 0;
|
|
|
|
const lastIndex = length - 1;
|
|
|
|
const result = [...array];
|
2021-11-09 06:04:34 +00:00
|
|
|
while (index < sampleNumber) {
|
2020-06-26 09:31:23 +00:00
|
|
|
const rand = index + Math.floor(Math.random() * (lastIndex - index + 1));
|
|
|
|
[result[rand], result[index]] = [result[index], result[rand]];
|
|
|
|
index += 1;
|
|
|
|
}
|
2021-11-09 06:04:34 +00:00
|
|
|
return result.slice(0, sampleNumber);
|
2020-06-26 09:31:23 +00:00
|
|
|
}
|