UNPKG

es-toolkit

Version:

A state-of-the-art, high-performance JavaScript utility library with a small bundle size and strong type annotations.

21 lines (18 loc) 619 B
import { randomInt } from '../math/randomInt.mjs'; function sampleSize(array, size) { if (size > array.length) { throw new Error('Size must be less than or equal to the length of array.'); } const result = new Array(size); const selected = new Set(); for (let step = array.length - size, resultIndex = 0; step < array.length; step++, resultIndex++) { let index = randomInt(0, step + 1); if (selected.has(index)) { index = step; } selected.add(index); result[resultIndex] = array[index]; } return result; } export { sampleSize };