Skip to main content
Module

x/simplestatistics/src/unique_count_sorted.js

simple statistics for node & browser javascript
Go to Latest
File
/** * 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, lastSeenValue; for (let i = 0; i < x.length; i++) { if (i === 0 || x[i] !== lastSeenValue) { lastSeenValue = x[i]; uniqueValueCount++; } } return uniqueValueCount;}
export default uniqueCountSorted;