UNPKG

1.9 kBJavaScriptView Raw
1/* globals Map: false */
2
3/**
4 * The [mode](https://en.wikipedia.org/wiki/Mode_%28statistics%29) is the number
5 * that appears in a list the highest number of times.
6 * There can be multiple modes in a list: in the event of a tie, this
7 * algorithm will return the most recently seen mode.
8 *
9 * modeFast uses a Map object to keep track of the mode, instead of the approach
10 * used with `mode`, a sorted array. As a result, it is faster
11 * than `mode` and supports any data type that can be compared with `==`.
12 * It also requires a
13 * [JavaScript environment with support for Map](https://kangax.github.io/compat-table/es6/#test-Map),
14 * and will throw an error if Map is not available.
15 *
16 * This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency):
17 * a method of finding a typical or central value of a set of numbers.
18 *
19 * @param {Array<*>} x a sample of one or more data points
20 * @returns {?*} mode
21 * @throws {ReferenceError} if the JavaScript environment doesn't support Map
22 * @throws {Error} if x is empty
23 * @example
24 * modeFast(['rabbits', 'rabbits', 'squirrels']); // => 'rabbits'
25 */
26function modeFast(x) {
27 // This index will reflect the incidence of different values, indexing
28 // them like
29 // { value: count }
30 const index = new Map();
31
32 // A running `mode` and the number of times it has been encountered.
33 let mode;
34 let modeCount = 0;
35
36 for (let i = 0; i < x.length; i++) {
37 let newCount = index.get(x[i]);
38 if (newCount === undefined) {
39 newCount = 1;
40 } else {
41 newCount++;
42 }
43 if (newCount > modeCount) {
44 mode = x[i];
45 modeCount = newCount;
46 }
47 index.set(x[i], newCount);
48 }
49
50 if (modeCount === 0) {
51 throw new Error("mode requires at last one data point");
52 }
53
54 return mode;
55}
56
57export default modeFast;