Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.

Commit 9fca9c7

Browse files
mgs96Kent C. Dodds
authored andcommitted
feat(arrayAverage): implements a function that calculates the average of the values of an array (#131)
1 parent 3d96524 commit 9fca9c7

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

src/array-average.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export default average
2+
3+
/**
4+
* Original source: https://stackoverflow.com/a/29544442/4573129
5+
* This method will return the average of an array
6+
* @param {Array} array - the array to calculate average
7+
* @return {Number} - the average of the values in the array
8+
*/
9+
10+
function average(array) {
11+
const sum = array.reduce((total, current) => {
12+
return total + current
13+
})
14+
return sum / array.length
15+
}

src/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import gcd from './gcd'
4646
import range from './range'
4747
import contains from './contains'
4848
import getOrdinalSuffix from './get-ordinal-suffix'
49+
import arrayAverage from './array-average'
4950

5051
export {
5152
isOdd,
@@ -96,4 +97,5 @@ export {
9697
range,
9798
contains,
9899
getOrdinalSuffix,
100+
arrayAverage,
99101
}

test/array-average.test.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import test from 'ava'
2+
import {arrayAverage} from '../src'
3+
4+
test('Calculates the average of an array', t => {
5+
const array = [1, 2, 3, 4]
6+
const expected = 2.5
7+
const actual = arrayAverage(array)
8+
t.deepEqual(actual, expected)
9+
})

0 commit comments

Comments
 (0)