compute-nanmedian

Computes the median of an array ignoring non-numeric values.

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
compute-nanmedian
301.0.18 years ago8 years agoMinified + gzip package size for compute-nanmedian in KB

Readme

nanmedian
!NPM versionnpm-imagenpm-url !Build Statustravis-imagetravis-url !Coverage Statuscoveralls-imagecoveralls-url !Dependenciesdependencies-imagedependencies-url
Computes the median of an array ignoring non-numeric values.

Installation

$ npm install compute-nanmedian

For 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.5

The function accepts two options:
  • sorted: boolean flag indicating if the input array is sorted in ascending order. Default: false.
  • accessor: accessor function for accessing values in object arrays.

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.5

For 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.5

Note: 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.js

Notes

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 test

All 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-cov

Istanbul creates a ./reports/coverage directory. To access an HTML version of the report,
$ make view-cov

License

MIT license.

Copyright

Copyright © 2015. Philipp Burckhardt.