7
7
const calculateMedian = require ( "./median.js" ) ;
8
8
9
9
describe ( "calculateMedian" , ( ) => {
10
- test ( "returns the median for odd length array" , ( ) => {
11
- expect ( calculateMedian ( [ 1 , 2 , 3 ] ) ) . toEqual ( 2 ) ;
12
- expect ( calculateMedian ( [ 1 , 2 , 3 , 4 , 5 ] ) ) . toEqual ( 3 ) ;
13
- } ) ;
10
+ [
11
+ { input : [ 1 , 2 , 3 ] , expected : 2 } ,
12
+ { input : [ 1 , 2 , 3 , 4 , 5 ] , expected : 3 } ,
13
+ { input : [ 1 , 2 , 3 , 4 ] , expected : 2.5 } ,
14
+ { input : [ 1 , 2 , 3 , 4 , 5 , 6 ] , expected : 3.5 } ,
15
+ ] . forEach ( ( { input, expected } ) =>
16
+ it ( `returns the median for [${ input } ]` , ( ) => expect ( calculateMedian ( input ) ) . toEqual ( expected ) )
17
+ ) ;
14
18
15
- test ( "returns the average of middle values for even length array" , ( ) => {
16
- expect ( calculateMedian ( [ 1 , 2 , 3 , 4 ] ) ) . toEqual ( 2.5 ) ;
17
- expect ( calculateMedian ( [ 1 , 2 , 3 , 4 , 5 , 6 ] ) ) . toEqual ( 3.5 ) ;
18
- } ) ;
19
+ [
20
+ { input : [ 3 , 1 , 2 ] , expected : 2 } ,
21
+ { input : [ 5 , 1 , 3 , 4 , 2 ] , expected : 3 } ,
22
+ { input : [ 4 , 2 , 1 , 3 ] , expected : 2.5 } ,
23
+ { input : [ 6 , 1 , 5 , 3 , 2 , 4 ] , expected : 3.5 } ,
24
+ ] . forEach ( ( { input, expected } ) =>
25
+ it ( `returns the correct median for unsorted array [${ input } ]` , ( ) => expect ( calculateMedian ( input ) ) . toEqual ( expected ) )
26
+ ) ;
19
27
20
- test ( "doesn't modify the input" , ( ) => {
28
+ it ( "doesn't modify the input array [1, 2, 3] " , ( ) => {
21
29
const list = [ 1 , 2 , 3 ] ;
22
30
calculateMedian ( list ) ;
23
-
24
31
expect ( list ) . toEqual ( [ 1 , 2 , 3 ] ) ;
25
32
} ) ;
26
- } ) ;
33
+
34
+ [ 'not an array' , 123 , null , undefined , { } , [ ] , [ "apple" , null , undefined ] ] . forEach ( val =>
35
+ it ( `returns null for non-numeric array (${ val } )` , ( ) => expect ( calculateMedian ( val ) ) . toBe ( null ) )
36
+ ) ;
37
+
38
+ [
39
+ { input : [ 1 , 2 , "3" , null , undefined , 4 ] , expected : 2 } ,
40
+ { input : [ "apple" , 1 , 2 , 3 , "banana" , 4 ] , expected : 2.5 } ,
41
+ { input : [ 1 , "2" , 3 , "4" , 5 ] , expected : 3 } ,
42
+ { input : [ 1 , "apple" , 2 , null , 3 , undefined , 4 ] , expected : 2.5 } ,
43
+ { input : [ 3 , "apple" , 1 , null , 2 , undefined , 4 ] , expected : 2.5 } ,
44
+ { input : [ "banana" , 5 , 3 , "apple" , 1 , 4 , 2 ] , expected : 3 } ,
45
+ ] . forEach ( ( { input, expected } ) =>
46
+ it ( `filters out non-numeric values and calculates the median for [${ input } ]` , ( ) => expect ( calculateMedian ( input ) ) . toEqual ( expected ) )
47
+ ) ;
48
+ } ) ;
0 commit comments