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+ */
1410
1511const 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+ }
1815
1916 // 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 )
2318
2419 // Divide sum by the length of the 'nums' array.
25- const avg = sum / nums . length
26- return avg
20+ return sum / nums . length
2721}
2822
2923export { mean }
Original file line number Diff line number Diff line change @@ -4,8 +4,18 @@ describe('Tests for average mean', () => {
44 it ( 'should be a function' , ( ) => {
55 expect ( typeof mean ) . toEqual ( 'function' )
66 } )
7+
8+ it ( 'should throw error for invalid input' , ( ) => {
9+ expect ( ( ) => mean ( 123 ) ) . toThrow ( )
10+ } )
11+
712 it ( 'should return the mean of an array of numbers' , ( ) => {
813 const meanFunction = mean ( [ 1 , 2 , 4 , 5 ] )
914 expect ( meanFunction ) . toBe ( 3 )
1015 } )
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+ } )
1121} )
You can’t perform that action at this time.
0 commit comments