Last active
November 18, 2015 22:10
-
-
Save chris-kobrzak/4ae7329f40c6c5c6758e to your computer and use it in GitHub Desktop.
Sample implementation of a median calculation function in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function calculateMedian( array ) { | |
var arraySize = array.length | |
if ( arraySize === 1 ) { | |
return array[0] | |
} | |
var isOddLength = isOdd( arraySize ), | |
middleIndex = Math.floor( arraySize / 2.0 ) | |
array.sort( subtract ) | |
if ( isOddLength ) { | |
return array[ middleIndex ] | |
} | |
return ( array[ middleIndex - 1] + array[ middleIndex ] ) / 2.0 | |
} | |
function subtract(a, b) { | |
return a - b | |
} | |
function isOdd( number ) { | |
return number % 2 === 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment