compute-nanmedian
v1.0.1
Published
Computes the median of an array ignoring non-numeric values.
Downloads
134
Readme
nanmedian
Computes the median of an array ignoring non-numeric values.
Installation
$ npm install compute-nanmedianFor use in the browser, use browserify.
Usage
var nanmedian = require( 'compute-nanmedian' );nanmedian( arr[, options] )
Computes the median of an array ignoring non-numeric values. For unsorted primitive arrays,
var unsorted = [ 5, null, 3, 2, 4, null ];
var m1 = nanmedian( unsorted );
// returns 3.5The function accepts two options:
sorted:booleanflag indicating if the inputarrayis sorted in ascending order. Default:false.accessor: accessorfunctionfor accessing values in objectarrays.
If the input array is already sorted in ascending order, set the sorted option to true.
var sorted = [ null, 2, 3, 4, null, 5 ];
var m2 = nanmedian( sorted, { 'sorted': true });
// returns 3.5For object arrays, provide an accessor function for accessing array values
var data = [
[1,5],
[2,null],
[3,3],
[4,2],
[5,4],
[6,null]
];
function getValue( d ) {
return d[ 1 ];
}
var m3 = nanmedian( data, {
'sorted': false,
'accessor': getValue
});
// returns 3.5Note: if provided an array which does not contain any numeric values, the function returns null.
Examples
var nanmedian = require( 'compute-nanmedian' );
var data = new Array( 1001 );
for ( var i = 0; i < data.length; i++ ) {
if ( i % 2 === 0 ) {
data[ i ] = null;
} else {
data[ i ] = Math.round( Math.random() * 100 );
}
}
console.log( nanmedian( data ) );To run the example code from the top-level application directory,
$ node ./examples/index.jsNotes
If provided an unsorted input array, the function is O( N log(N) ), where N is the array length. If the array is already sorted in ascending order, the function is O(N) as the function still needs to make a single linear pass to extract numeric values from the array.
Tests
Unit
Unit tests use the Mocha test framework with Chai assertions. To run the tests, execute the following command in the top-level application directory:
$ make testAll new feature development should have corresponding unit tests to validate correct functionality.
Test Coverage
This repository uses Istanbul as its code coverage tool. To generate a test coverage report, execute the following command in the top-level application directory:
$ make test-covIstanbul creates a ./reports/coverage directory. To access an HTML version of the report,
$ make view-covLicense
Copyright
Copyright © 2015. Philipp Burckhardt.
