Skip to content

Instantly share code, notes, and snippets.

@chris-kobrzak
Last active November 18, 2015 22:10
Show Gist options
  • Save chris-kobrzak/4ae7329f40c6c5c6758e to your computer and use it in GitHub Desktop.
Save chris-kobrzak/4ae7329f40c6c5c6758e to your computer and use it in GitHub Desktop.
Sample implementation of a median calculation function in JavaScript
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