sample.js

import shuffle from "./shuffle.js";

/**
 * 从给定的包含 `n` 个元素的数组中创建一个[简单随机样本](http://en.wikipedia.org/wiki/Simple_random_sample)。
 *
 * 采样值可以是任意顺序,不一定与输入中的顺序相同。
 *
 * @param {Array<any>} x 输入数组,可以包含任何类型
 * @param {number} n 需要采样的元素数量
 * @param {Function} [randomSource=Math.random] 一个可选的熵源,返回 [0, 1) 范围内的数字
 * @return {Array} 原始数组中的 `n` 个元素的子集
 *
 * @example
 * var values = [1, 2, 4, 5, 6, 7, 8, 9];
 * sample(values, 3); // 返回 3 个随机值,例如 [2, 5, 8];
 */
function sample(x, n, randomSource) {
    // 使用 Fisher-Yates 洗牌算法对原始数组进行洗牌
    const shuffled = shuffle(x, randomSource);

    // 然后返回其子集 - 前 `n` 个元素
    return shuffled.slice(0, n);
}

export default sample;