Skip to content

Commit

Permalink
feat(mean): combineMeans, a method for combining calculated means
Browse files Browse the repository at this point in the history
* Adding combineMeans

* Avoiding repetition

* Fixing unit test formulation
  • Loading branch information
Yomguithereal authored and tmcw committed Feb 28, 2017
1 parent 9647e36 commit d9e3ebc
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.js
Expand Up @@ -50,6 +50,7 @@ ss.combinationsReplacement = require('./src/combinations_replacement');

// measures of centrality
ss.addToMean = require('./src/add_to_mean');
ss.combineMeans = require('./src/combine_means');
ss.geometricMean = require('./src/geometric_mean');
ss.harmonicMean = require('./src/harmonic_mean');
ss.mean = ss.average = require('./src/mean');
Expand Down
24 changes: 24 additions & 0 deletions src/combine_means.js
@@ -0,0 +1,24 @@
'use strict';
/* @flow */

/**
* When combining two lists of values for which one already knows the means,
* one does not have to necessary recompute the mean of the combined lists in
* linear time. They can instead use this function to compute the combined
* mean by providing the mean & number of values of the first list and the mean
* & number of values of the second list.
*
* @param {number} mean1 mean of the first list
* @param {number} n1 number of items in the first list
* @param {number} mean2 mean of the second list
* @param {number} n2 number of items in the second list
* @returns {number} the combined mean
*
* @example
* combineMeans(5, 3, 4, 3); // => 4.5
*/
function combineMeans(mean1 /*: number*/, n1/*: number */, mean2 /*: number*/, n2/*: number */)/*: number */ {
return (mean1 * n1 + mean2 * n2) / (n1 + n2);
}

module.exports = combineMeans;
16 changes: 16 additions & 0 deletions test/combine_means.js
@@ -0,0 +1,16 @@
/* eslint no-shadow: 0 */
'use strict';

var test = require('tap').test;
var ss = require('../');

test('combineMeans', function(t) {
t.test('can combine the means of two lists', function(t) {
var values1 = [8, 3, 4];
var values2 = [2, 6, 4];
t.equal(ss.combineMeans(ss.mean(values1), values1.length, ss.mean(values2), values2.length), 4.5);
t.equal(ss.combineMeans(ss.mean(values1), values1.length, ss.mean(values2), values2.length), ss.mean(values1.concat(values2)));
t.end();
});
t.end();
});

0 comments on commit d9e3ebc

Please sign in to comment.