source: node_modules/es-toolkit/dist/array/sampleSize.mjs

Last change on this file was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago

Added visualizations

  • Property mode set to 100644
File size: 619 bytes
Line 
1import { randomInt } from '../math/randomInt.mjs';
2
3function sampleSize(array, size) {
4 if (size > array.length) {
5 throw new Error('Size must be less than or equal to the length of array.');
6 }
7 const result = new Array(size);
8 const selected = new Set();
9 for (let step = array.length - size, resultIndex = 0; step < array.length; step++, resultIndex++) {
10 let index = randomInt(0, step + 1);
11 if (selected.has(index)) {
12 index = step;
13 }
14 selected.add(index);
15 result[resultIndex] = array[index];
16 }
17 return result;
18}
19
20export { sampleSize };
Note: See TracBrowser for help on using the repository browser.