UNPKG

@yanick/remeda-extra

Version:

A handful of added functions for Remeda

25 lines (24 loc) 820 B
import { purry } from 'remeda'; function _sample(items, options) { let nbrSamples = typeof options === 'number' ? options : options.size; const repeating = typeof options === 'object' && (options === null || options === void 0 ? void 0 : options.repeating); let size = items.length; // we only need a copy if we're in non-repeating mode if (!repeating) items = [...items]; if (nbrSamples > size && !repeating) nbrSamples = size; const sample = []; for (let i = 0; i < nbrSamples; i++) { const index = Math.floor(Math.random() * size); sample.push(items[index]); if (!repeating) { items[index] = items[size - 1]; size--; } } return sample; } export function sample() { return purry(_sample, arguments); }