forked from ChristianNally/web-2023-Feb-06-west-samples
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathq0.js
More file actions
107 lines (87 loc) · 2.07 KB
/
q0.js
File metadata and controls
107 lines (87 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/* Question 0
*
* Implement the functions defined below
*
*/
/* ===========================================================================
* COUNT - the number of items in a list
*
* For example:
*
* count([6,2,3,4,9,6,1,0,5]);
*
* Returns:
*
* 9
*/
const count = function(arr) {
const numElements = arr.length;
return numElements;
return arr.length;
};
/* ===========================================================================
* SUM - the sum of the numbers in a list
- safe to assume that all items are numbers already
*
* For example:
*
* sum([6,2,3,4,9,6,1,0,5])
*
* Returns:
*
* 36
*/
const sum = function(arr) {
// could be solved with .reduce
const reducedVal1 = arr.reduce((runningTotal, number) => {
return runningTotal + number;
}, 0);
return reducedVal1;
// create a space in memory to hold the running total
let runningTotal = 0;
// look at each element inside the array
// for (const number of arr) {
// // add the current element to the running total
// runningTotal = runningTotal + number;
// // runningTotal += number;
// }
arr.forEach((number) => {
runningTotal += number;
});
// return the running total
return runningTotal;
};
// To be used by mean. Do not alter.
const round = function(number) {
return Math.round(number * 100) / 100;
};
// 3.141587
// 314.1587
// 314
// 3.14
/* ===========================================================================
* MEAN - the average value of numbers in a list
* - use the provided 'round' function when returning your value
* - if empty array, return null to indicate that mean cannot be calculated
*
* For example:
*
* mean([6,2,3,4,9,6,1,0,5])
*
* Returns:
*
* 4
*/
const mean = function(arr) {
if (arr.length === 0) {
return null;
}
// avg = totalOfElements / numOfElements
const total = sum(arr);
const numElements = count(arr);
const avg = total / numElements;
const roundedAvg = round(avg);
return roundedAvg;
};
// Don't change below:
module.exports = { count, sum, mean };