File tree Expand file tree Collapse file tree 1 file changed +22
-3
lines changed
Expand file tree Collapse file tree 1 file changed +22
-3
lines changed 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- const middleIndex = Math . floor ( list . length / 2 ) ;
10- const median = list . splice ( middleIndex , 1 ) [ 0 ] ;
11- return median ;
9+
10+ // first of all, checking if 'list' is an array
11+ if ( Array . isArray ( list ) ) {
12+
13+ const filteredArr = list . filter ( x => typeof x === 'number' ) ;
14+
15+ if ( filteredArr . length < 2 ) {
16+ return null ;
17+ }
18+
19+ // using 'spread operator' copies the array without mutating it
20+ const sortedList = [ ...filteredArr ] . sort ( ( a , b ) => a - b ) ;
21+
22+ const middleIndex = Math . floor ( sortedList . length / 2 ) ;
23+
24+ if ( sortedList . length % 2 === 0 ) {
25+ return ( sortedList [ middleIndex - 1 ] + sortedList [ middleIndex ] ) / 2 ;
26+ } else {
27+ return sortedList [ middleIndex ]
28+ }
29+ }
30+ return null ;
1231}
1332
1433module . exports = calculateMedian ;
You can’t perform that action at this time.
0 commit comments