Skip to content

Commit 11e30f5

Browse files
committed
Add initial implementation of mean calculation and tests
1 parent 5aa1295 commit 11e30f5

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

prep/mean.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
Let’s consider a list of prices in a bill:
3+
4.6, 5.03, 7.99, 8.01
4+
instead of writing the like below
5+
const price0 = 4.6;
6+
const price1 = 5.03;
7+
const price2 = 7.99;
8+
const price3 = 8.01;
9+
We can write it as an array literal
10+
const items = [4.6, 5.03, 7.99, 8.01];
11+
12+
The Array object, as with arrays in other programming languages, enables storing a collection
13+
of multiple items under a single variable name, and has members for performing common array operations.
14+
Arrays can store items of any type & multiple pieces of information.
15+
16+
In JavaScript, we can use [] notation to access specific elements in the array using index numbers.
17+
The index numbers start from 0.
18+
19+
20+
const items = [4.6, 5.03, 7.99, 8.01];
21+
console.log(items[0]); // 4.6
22+
console.log(items[1]); // 5.03
23+
console.log(items[2]); // 7.99
24+
console.log(items[3]); // 8.01
25+
// Accessing elements using index numbers
26+
*/
27+
const items = [4.6, 5.03, 7.99, 8.01];
28+
function calculateMean(list) {
29+
// Calculate the sum of all elements in the array
30+
const sum = list.reduce(
31+
(accumulator, currentValue) => accumulator + currentValue,
32+
0
33+
);
34+
// Calculate the mean by dividing the sum by the number of elements
35+
const mean = sum / list.length;
36+
return mean;
37+
}

prep/mean.test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/*
2+
test("does something as described below", () => {
3+
// test implementation goes here
4+
});
5+
*/
6+
test("calculates the mean of a list of numbers", () => {
7+
const list = [3, 50, 7];
8+
const currentOutput = calculateMean(list);
9+
const targetOutput = 20;
10+
11+
expect(currentOutput).toEqual(targetOutput); // 20 is (3 + 50 + 7) / 3
12+
});

prep/package.json

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "prep",
3+
"version": "1.0.0",
4+
"description": "",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "jest"
8+
},
9+
"keywords": [],
10+
"author": "",
11+
"license": "ISC",
12+
"type": "commonjs",
13+
"devDependencies": {
14+
"jest": "^30.2.0"
15+
}
16+
}

0 commit comments

Comments
 (0)