File tree Expand file tree Collapse file tree 2 files changed +24
-20
lines changed Expand file tree Collapse file tree 2 files changed +24
-20
lines changed Original file line number Diff line number Diff line change 1
- 'use strict'
2
- /*
3
- author: PatOnTheBack
4
- license: GPL-3.0 or later
5
-
6
- Modified from:
7
- https://github.com/TheAlgorithms/Python/blob/master/maths/average.py
8
-
9
- This script will find the average (mean) of an array of numbers.
10
-
11
- More about mean:
12
- https://en.wikipedia.org/wiki/Mean
13
- */
1
+ /**
2
+ * @function mean
3
+ * @description This script will find the mean value of a array of numbers.
4
+ * @param {Integer[] } nums - Array of integer
5
+ * @return {Integer } - mean of nums.
6
+ * @see [Mean](hhttps://en.wikipedia.org/wiki/Mean)
7
+ * @example mean([1, 2, 4, 5]) = 3
8
+ * @example mean([10, 40, 100, 20]) = 42.5
9
+ */
14
10
15
11
const mean = ( nums ) => {
16
- // This is a function returns average/mean of array
17
- let sum = 0
12
+ if ( ! Array . isArray ( nums ) ) {
13
+ throw new TypeError ( 'Invalid Input' )
14
+ }
18
15
19
16
// This loop sums all values in the 'nums' array using forEach loop
20
- nums . forEach ( function ( current ) {
21
- sum += current
22
- } )
17
+ const sum = nums . reduce ( ( sum , cur ) => sum + cur , 0 )
23
18
24
19
// Divide sum by the length of the 'nums' array.
25
- const avg = sum / nums . length
26
- return avg
20
+ return sum / nums . length
27
21
}
28
22
29
23
export { mean }
Original file line number Diff line number Diff line change @@ -4,8 +4,18 @@ describe('Tests for average mean', () => {
4
4
it ( 'should be a function' , ( ) => {
5
5
expect ( typeof mean ) . toEqual ( 'function' )
6
6
} )
7
+
8
+ it ( 'should throw error for invalid input' , ( ) => {
9
+ expect ( ( ) => mean ( 123 ) ) . toThrow ( )
10
+ } )
11
+
7
12
it ( 'should return the mean of an array of numbers' , ( ) => {
8
13
const meanFunction = mean ( [ 1 , 2 , 4 , 5 ] )
9
14
expect ( meanFunction ) . toBe ( 3 )
10
15
} )
16
+
17
+ it ( 'should return the mean of an array of numbers' , ( ) => {
18
+ const meanFunction = mean ( [ 10 , 40 , 100 , 20 ] )
19
+ expect ( meanFunction ) . toBe ( 42.5 )
20
+ } )
11
21
} )
You can’t perform that action at this time.
0 commit comments