File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 77
88
99function calculateMedian ( list ) {
10- // chekc it is an rray
10+ // Check it is an array
1111 if ( ! Array . isArray ( list ) ) return null ;
1212
13- // pull out numbers
13+ // Pull out numbers
1414 const nums = list . filter ( n => typeof n === "number" && ! Number . isNaN ( n ) ) ;
1515
16- // If no numbers, return null
16+ // If no numbers, return null
1717 if ( nums . length === 0 ) return null ;
1818
19- // Sort without changing original array
20- const sorted = [ ... nums ] . sort ( ( a , b ) => a - b ) ;
19+ // MODERN FIX: Use .toSorted() to avoid mutating the original array
20+ const sorted = nums . toSorted ( ( a , b ) => a - b ) ;
2121
2222 const len = sorted . length ;
2323 const mid = Math . floor ( len / 2 ) ;
2424
25- // If length is odd, take middle element
25+ // If length is odd, take middle element
2626 if ( len % 2 === 1 ) {
2727 return sorted [ mid ] ;
2828 }
2929
30- // If length is even take average of two middle elements
30+ // If length is even, take average of two middle elements
3131 return ( sorted [ mid - 1 ] + sorted [ mid ] ) / 2 ;
3232}
3333
Original file line number Diff line number Diff line change 1- sum . js
1+
22function sum ( arr ) {
3+ if ( ! Array . isArray ( arr ) ) return 0 ;
4+
35 return arr . reduce ( ( accumulator , currentValue ) => {
4- if ( typeof currentValue === 'number' && ! isNaN ( currentValue ) ) { // investigate if the current element is a number and not NaN
5- return accumulator + currentValue ;
6+ // 1. Convert the value to a Number (handles strings like "10")
7+ const numericValue = Number ( currentValue ) ;
8+
9+ // 2. Check if the result is a valid number and not NaN
10+ // Note: Number.isNaN is stricter/safer than the global isNaN
11+ if ( ! Number . isNaN ( numericValue ) && typeof currentValue !== 'boolean' && currentValue !== null ) {
12+ return accumulator + numericValue ;
613 }
7- return accumulator ; // If not a number, return current sum
8- } , 0 ) ; // This line initialize sum at 0 for empty arrays
14+
15+ return accumulator ;
16+ } , 0 ) ;
917}
1018
11- module . exports = sum ;
19+ module . exports = sum ;
You can’t perform that action at this time.
0 commit comments