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- const middleIndex = Math . floor ( list . length / 2 ) ;
10- const median = list . splice ( middleIndex , 1 ) [ 0 ] ;
11- return median ;
9+ // Return null immediately if the input is not an array
10+ if ( ! Array . isArray ( list ) ) {
11+ return null ;
12+ }
13+
14+ // Keep only real numeric values
15+ const numbersOnly = list . filter (
16+ ( item ) => typeof item === "number" && ! Number . isNaN ( item )
17+ ) ;
18+
19+ // Return null if the array contains no numbers
20+ if ( numbersOnly . length === 0 ) {
21+ return null ;
22+ }
23+
24+ // Create a sorted copy so the original input is not changed
25+ const sortedNumbers = [ ...numbersOnly ] . sort ( ( a , b ) => a - b ) ;
26+
27+ const middleIndex = Math . floor ( sortedNumbers . length / 2 ) ;
28+
29+ // For an even-length array, median is the average of the two middle values
30+ if ( sortedNumbers . length % 2 === 0 ) {
31+ return ( sortedNumbers [ middleIndex - 1 ] + sortedNumbers [ middleIndex ] ) / 2 ;
32+ }
33+
34+ // For an odd-length array, median is the middle value
35+ return sortedNumbers [ middleIndex ] ;
1236}
1337
1438module . exports = calculateMedian ;
You can’t perform that action at this time.
0 commit comments