super-utils-plus
Version:
A superior alternative to Lodash with improved performance, TypeScript support, and developer experience
50 lines (49 loc) • 1.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.shuffle = shuffle;
exports.sample = sample;
exports.sampleSize = sampleSize;
const random_1 = require("../utils/random");
/**
* Creates an array of shuffled values using a version of the Fisher-Yates shuffle.
*
* @param array - The array to shuffle
* @returns The shuffled array
*/
function shuffle(array) {
if (!array || !array.length) {
return [];
}
const result = [...array];
for (let index = result.length - 1; index > 0; index--) {
const randomIndex = (0, random_1.randomInt)(0, index);
[result[index], result[randomIndex]] = [result[randomIndex], result[index]];
}
return result;
}
/**
* Gets a random element from an array.
*
* @param array - The array to sample from
* @returns The sampled element
*/
function sample(array) {
if (!array || !array.length) {
return undefined;
}
return array[(0, random_1.randomInt)(0, array.length - 1)];
}
/**
* Gets `n` unique random elements from an array.
*
* @param array - The array to sample from
* @param n - The number of elements to sample
* @returns The sampled elements
*/
function sampleSize(array, n = 1) {
if (!array || !array.length || n <= 0) {
return [];
}
const size = Math.min(Math.floor(n), array.length);
return shuffle(array).slice(0, size);
}