Skip to content

Commit 3cb29a0

Browse files
committed
Refactor mean calculation and tests for clarity and functionality
1 parent 11e30f5 commit 3cb29a0

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

prep/mean.js

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ console.log(items[1]); // 5.03
2323
console.log(items[2]); // 7.99
2424
console.log(items[3]); // 8.01
2525
// Accessing elements using index numbers
26-
*/
26+
2727
const items = [4.6, 5.03, 7.99, 8.01];
2828
function calculateMean(list) {
2929
// Calculate the sum of all elements in the array
@@ -35,3 +35,25 @@ function calculateMean(list) {
3535
const mean = sum / list.length;
3636
return mean;
3737
}
38+
*/
39+
//const list = [4.6, 5.03, 7.99, 8.01];
40+
function calculateMean(list) {
41+
//1. sum the elements of the array
42+
let sum = 0;
43+
for (let i = 0; i < list.length; i++) {
44+
const arrayInValue = Number(list);
45+
if (typeof list[i] === "number" && !isNaN(list[i])) {
46+
sum += list[i];
47+
}
48+
}
49+
//2. determine the length of the array
50+
let count = list.length;
51+
//3. divide #1 by #2
52+
const mean = sum / count;
53+
//4. return #3
54+
return mean;
55+
}
56+
console.log(calculateMean([4.6, 5.03, 7.99, 8.01]));
57+
console.log(calculateMean([3, "50", 7]));
58+
59+
//module.exports = calculateMean;

prep/mean.test.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,25 @@
22
test("does something as described below", () => {
33
// test implementation goes here
44
});
5+
6+
57
*/
8+
//mean.test.js
9+
const mean = require("./mean"); // Import the mean function from mean.js
10+
test("calculates the mean of a list of numbers", () => {
11+
expect(mean([3, 50, 7])).toBe(20); // 20 is (3 + 50 + 7) / 3
12+
expect(mean([4.6, 5.03, 7.99, 8.01])).toBeCloseTo(6.4075); // 6.4075 is (4.6 + 5.03 + 7.99 + 8.01) / 4
13+
expect(mean([10, 20, 30, 40, 50])).toBe(30); // 30 is (10 + 20 + 30 + 40 + 50) / 5
14+
expect(mean([1, 2, 3, 4, 5, 6])).toBe(3.5); // 3.5 is (1 + 2 + 3 + 4 + 5 + 6) / 6
15+
});
16+
/*
17+
The expect statement is used to create an assertion that checks if the output of the mean function matches the expected value.
618
test("calculates the mean of a list of numbers", () => {
719
const list = [3, 50, 7];
820
const currentOutput = calculateMean(list);
921
const targetOutput = 20;
1022
1123
expect(currentOutput).toEqual(targetOutput); // 20 is (3 + 50 + 7) / 3
1224
});
25+
26+
*/

0 commit comments

Comments
 (0)