File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 66// or 'list' has mixed values (the function is expected to sort only numbers).
77
88function calculateMedian ( list ) {
9- if ( Array . isArray ( list ) ) {
10- let newList = list . filter ( item => typeof item === "number" ) ;
11- newList = newList . sort ( function ( a , b ) {
12- return a - b ;
13- } ) ;
14- if ( newList . length > 0 ) {
15- const middleIndex = Math . floor ( newList . length / 2 ) ;
16- const median = newList [ middleIndex ]
17- if ( newList . length % 2 !== 0 ) {
18- return median ;
9+ // if list is not an array, stop the function and return null
10+ if ( ! Array . isArray ( list ) ) {
11+ return null ;
12+ }
13+
14+ // the list is filtered to get only the numbers, then sorted in ascending order
15+ let newList = list . filter ( item => Number . isFinite ( item ) ) ;
16+ newList = newList . sort ( function ( a , b ) { return a - b } ) ;
17+
18+ // here we check if the list is empty, if not we calculate the median
19+ if ( newList . length > 0 ) {
20+ const middleIndex = Math . floor ( newList . length / 2 ) ;
21+ const median = newList [ middleIndex ]
22+ if ( newList . length % 2 !== 0 ) {
23+ return median ;
1924 }
20- else return ( newList [ middleIndex - 1 ] + median ) / 2 }
21- else return null ; }
22- else return null ;
25+ return ( newList [ middleIndex - 1 ] + median ) / 2 ;
26+ }
27+ return null ;
2328}
2429
2530module . exports = calculateMedian ;
You can’t perform that action at this time.
0 commit comments