File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 55// Hint: Please consider scenarios when 'list' doesn't have numbers (the function is expected to return null)
66// or 'list' has mixed values (the function is expected to sort only numbers).
77
8+
89function calculateMedian ( list ) {
9- const middleIndex = Math . floor ( list . length / 2 ) ;
10- const median = list . splice ( middleIndex , 1 ) [ 0 ] ;
11- return median ;
10+ // chekc it is an rray
11+ if ( ! Array . isArray ( list ) ) return null ;
12+
13+ // pull out numbers
14+ const nums = list . filter ( n => typeof n === "number" && ! Number . isNaN ( n ) ) ;
15+
16+ // If no numbers, return null
17+ if ( nums . length === 0 ) return null ;
18+
19+ // Sort without changing original array
20+ const sorted = [ ...nums ] . sort ( ( a , b ) => a - b ) ;
21+
22+ const len = sorted . length ;
23+ const mid = Math . floor ( len / 2 ) ;
24+
25+ // If length is odd, take middle element
26+ if ( len % 2 === 1 ) {
27+ return sorted [ mid ] ;
28+ }
29+
30+ // If length is even take average of two middle elements
31+ return ( sorted [ mid - 1 ] + sorted [ mid ] ) / 2 ;
1232}
1333
14- module . exports = calculateMedian ;
34+ module . exports = calculateMedian ;
Original file line number Diff line number Diff line change 1- function dedupe ( ) { }
1+ function dedupe ( arr ) {
2+ // The spread operator [...] converts back to an array.
3+ return [ ...new Set ( arr ) ] ; //New Set(arr) removes duplicates automatically
4+ }
Original file line number Diff line number Diff line change 1- function findMax ( elements ) {
1+
2+ function findMax ( arr ) {
3+ // filter out non-numbers, non-numeric strings, and NaN. ALso convert string numbers to number
4+ const numericValues = arr
5+ . filter ( ( item ) => typeof item === "number" || ( typeof item === "string" && item . trim ( ) !== "" && ! isNaN ( item ) ) )
6+ . map ( ( item ) => Number ( item ) ) ;
7+
8+ // returns -Infinity i no numerical elements are found
9+ if ( numericValues . length === 0 ) return - Infinity ;
10+
11+ return Math . max ( ...numericValues ) ;
212}
313
414module . exports = findMax ;
Original file line number Diff line number Diff line change 1- function sum ( elements ) {
1+ sum . js
2+ function sum ( arr ) {
3+ 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+ }
7+ return accumulator ; // If not a number, return current sum
8+ } , 0 ) ; // This line initialize sum at 0 for empty arrays
29}
310
411module . exports = sum ;
You can’t perform that action at this time.
0 commit comments