From facc6aa3ad2888a5649a0b3a3cf801bf40668e88 Mon Sep 17 00:00:00 2001 From: Eetu Huisman Date: Thu, 9 Jul 2015 16:39:21 +0300 Subject: [PATCH] [FIX] Maximum value assignment The maximum should only be assigned if the count of the current value is greater than the maximum, not every time it is not the same. --- lib/index.js | 2 +- test/test.js | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/index.js b/lib/index.js index a0c7880..15b740d 100644 --- a/lib/index.js +++ b/lib/index.js @@ -44,7 +44,7 @@ function mode( arr, clbk ) { count[ val ] += 1; if ( count[ val ] === max ) { vals.push( val ); - } else { + } else if ( count[ val ] > max ) { max = count[ val ]; vals = [ val ]; } diff --git a/test/test.js b/test/test.js index c398393..b5914c8 100644 --- a/test/test.js +++ b/test/test.js @@ -76,6 +76,9 @@ describe( 'compute-mode', function tests() { data = [ 2, 4, 5, 3, 8, 4, 2 ]; assert.deepEqual( mode( data ), [ 2, 4 ] ); + + data = [ 2, 2, 4 ]; + assert.deepEqual( mode( data ), [ 2 ] ); }); it( 'should compute the mode using an accessor', function test() { @@ -110,6 +113,17 @@ describe( 'compute-mode', function tests() { assert.deepEqual( actual, expected ); + data = [ + {'x':2}, + {'x':2}, + {'x':4} + ]; + + actual = mode( data, getValue ); + expected = [ 2 ]; + + assert.deepEqual( actual, expected ); + function getValue( d ) { return d.x; }