-
Notifications
You must be signed in to change notification settings - Fork 224
/
mode.js
28 lines (26 loc) · 1011 Bytes
/
mode.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import modeSorted from "./mode_sorted.js";
import numericSort from "./numeric_sort.js";
/**
* The [mode](https://en.wikipedia.org/wiki/Mode_%28statistics%29) is the number
* that appears in a list the highest number of times.
* There can be multiple modes in a list: in the event of a tie, this
* algorithm will return the most recently seen mode.
*
* This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency):
* a method of finding a typical or central value of a set of numbers.
*
* This runs in `O(n log(n))` because it needs to sort the array internally
* before running an `O(n)` search to find the mode.
*
* @param {Array<number>} x input
* @returns {number} mode
* @example
* mode([0, 0, 1]); // => 0
*/
function mode(x) {
// Sorting the array lets us iterate through it below and be sure
// that every time we see a new number it's new and we'll never
// see the same number twice
return modeSorted(numericSort(x));
}
export default mode;