equal_interval_breaks.js

import max from "./max.js";
import min from "./min.js";

/**
 * 给定一个数组 x,此函数将找到 x 的范围,并返回一个可用于将 x 分类为多个类别的断点数组。
 * 返回的数组总是比类别数多 1,因为它包含最小值。
 *
 * @param {Array<number>} x 一个数值数组
 * @param {number} nClasses 所需的类别数
 * @returns {Array<number>} 类别断点位置的数组
 * @example
 * equalIntervalBreaks([1, 2, 3, 4, 5, 6], 4); // => [1, 2.25, 3.5, 4.75, 6]
 */
function equalIntervalBreaks(x, nClasses) {
    if (x.length < 2) {
        return x;
    }

    const theMin = min(x);
    const theMax = max(x);

    // 第一个断点总是数据集中的最小值
    const breaks = [theMin];

    // 每个断点的大小是数据集的全范围除以所需的类别数
    const breakSize = (theMax - theMin) / nClasses;

    // 在 nClasses = 1 的情况下,此循环不会运行
    // 返回的断点将是 [min, max]
    for (let i = 1; i < nClasses; i++) {
        breaks.push(breaks[0] + breakSize * i);
    }

    // 最后一个断点总是最大值
    breaks.push(theMax);

    return breaks;
}

export default equalIntervalBreaks;