simple-statistics
Version:
28 lines (26 loc) • 805 B
JavaScript
/**
* For a sorted input, counting the number of unique values
* is possible in constant time and constant memory. This is
* a simple implementation of the algorithm.
*
* Values are compared with `===`, so objects and non-primitive objects
* are not handled in any special way.
*
* @param {Array<*>} x an array of any kind of value
* @returns {number} count of unique values
* @example
* uniqueCountSorted([1, 2, 3]); // => 3
* uniqueCountSorted([1, 1, 1]); // => 1
*/
function uniqueCountSorted(x) {
let uniqueValueCount = 0;
let lastSeenValue;
for (let i = 0; i < x.length; i++) {
if (i === 0 || x[i] !== lastSeenValue) {
lastSeenValue = x[i];
uniqueValueCount++;
}
}
return uniqueValueCount;
}
export default uniqueCountSorted;