UNPKG

805 BJavaScriptView Raw
1/**
2 * For a sorted input, counting the number of unique values
3 * is possible in constant time and constant memory. This is
4 * a simple implementation of the algorithm.
5 *
6 * Values are compared with `===`, so objects and non-primitive objects
7 * are not handled in any special way.
8 *
9 * @param {Array<*>} x an array of any kind of value
10 * @returns {number} count of unique values
11 * @example
12 * uniqueCountSorted([1, 2, 3]); // => 3
13 * uniqueCountSorted([1, 1, 1]); // => 1
14 */
15function uniqueCountSorted(x) {
16 let uniqueValueCount = 0,
17 lastSeenValue;
18 for (let i = 0; i < x.length; i++) {
19 if (i === 0 || x[i] !== lastSeenValue) {
20 lastSeenValue = x[i];
21 uniqueValueCount++;
22 }
23 }
24 return uniqueValueCount;
25}
26
27export default uniqueCountSorted;