Skip to content

Commit

Permalink
Fix mode calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
plegner committed Sep 25, 2024
1 parent c9482fb commit 2ad1b94
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
19 changes: 8 additions & 11 deletions src/statistics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,14 @@ export function mode(values: number[]) {
let result: number|undefined = undefined;

for (const v of values) {
if (!counts.has(v)) {
counts.set(v, 1);
} else {
const newCount = counts.get(v)! + 1;
counts.set(v, newCount);
if (newCount === maxCount) {
result = undefined;
} else if (newCount > maxCount) {
maxCount = newCount;
result = v;
}
if (!counts.has(v)) counts.set(v, 0);
const newCount = counts.get(v)! + 1;
counts.set(v, newCount);
if (newCount === maxCount) {
result = undefined;
} else if (newCount > maxCount) {
maxCount = newCount;
result = v;
}
}

Expand Down
13 changes: 12 additions & 1 deletion test/statistics-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,20 @@


import tape from 'tape';
import {quantile} from '../src';
import {mode, quantile} from '../src';


tape('mode', (test) => {
test.equal(mode([]), undefined);
test.equal(mode([2]), 2);
test.equal(mode([2, 3]), undefined);
test.equal(mode([2, 3, 3]), 3);
test.equal(mode([2, 2, 3, 3, 4]), undefined);
test.equal(mode([2, 2, 2, 3, 3, 4]), 2);

test.end();
});

tape('quantile', (test) => {
test.equal(quantile([], 0.5), 0);

Expand Down

0 comments on commit 2ad1b94

Please sign in to comment.