UNPKG

1.35 kBJavaScriptView Raw
1import max from "./max";
2import min from "./min";
3
4/**
5 * Given an array of x, this will find the extent of the
6 * x and return an array of breaks that can be used
7 * to categorize the x into a number of classes. The
8 * returned array will always be 1 longer than the number of
9 * classes because it includes the minimum value.
10 *
11 * @param {Array<number>} x an array of number values
12 * @param {number} nClasses number of desired classes
13 * @returns {Array<number>} array of class break positions
14 * @example
15 * equalIntervalBreaks([1, 2, 3, 4, 5, 6], 4); // => [1, 2.25, 3.5, 4.75, 6]
16 */
17function equalIntervalBreaks(x, nClasses) {
18 if (x.length < 2) {
19 return x;
20 }
21
22 const theMin = min(x);
23 const theMax = max(x);
24
25 // the first break will always be the minimum value
26 // in the xset
27 const breaks = [theMin];
28
29 // The size of each break is the full range of the x
30 // divided by the number of classes requested
31 const breakSize = (theMax - theMin) / nClasses;
32
33 // In the case of nClasses = 1, this loop won't run
34 // and the returned breaks will be [min, max]
35 for (let i = 1; i < nClasses; i++) {
36 breaks.push(breaks[0] + breakSize * i);
37 }
38
39 // the last break will always be the
40 // maximum.
41 breaks.push(theMax);
42
43 return breaks;
44}
45
46export default equalIntervalBreaks;