Skip to content

Commit 9f4ff1e

Browse files
committed
Finished exercises in class
1 parent 0f94b74 commit 9f4ff1e

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

src/functions-and-arrays.js

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,86 @@
11
// Iteration #1: Find the maximum
2+
function maxOfTwoNumbers(a, b) {
3+
return Math.max(a, b);
4+
}
25

36
// Iteration #2: Find longest word
47
const words = ['mystery', 'brother', 'aviator', 'crocodile', 'pearl', 'orchard', 'crackpot'];
58

9+
function findLongestWord(arr) {
10+
11+
let size = 0;
12+
let longestWord = null;
13+
14+
for(let i = 0; i < arr.length; i++) {
15+
if (arr[i].length > size) {
16+
size = arr[i].length;
17+
longestWord = arr[i];
18+
}
19+
}
20+
21+
return longestWord;
22+
}
23+
624
// Iteration #3: Calculate the sum
725

826
const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10];
927

28+
function sumNumbers(arr) {
29+
30+
if (arr.length === 0) {
31+
return 0;
32+
}
33+
34+
sum(arr);
35+
return total;
36+
/*
37+
38+
let total = 0;
39+
40+
for(let i = 0; i < arr.length; i++) {
41+
total += arr[i];
42+
}
43+
return total;
44+
}
45+
*/
46+
47+
// Iteration #3 BONUS
48+
49+
function sum(arr) {
50+
51+
if (arr.length === 0) {
52+
return 0;
53+
}
54+
55+
let total = 0;
56+
57+
for(let i = 0; i < arr.length; i++) {
58+
if(typeof arr[i] === "number") {
59+
total += arr[i];
60+
} else if (typeof arr[i] === "boolean") {
61+
total += total + arr[i];
62+
} else if (typeof arr[i] === "string") {
63+
total += arr[i].length;
64+
}
65+
}
66+
return total;
67+
}
68+
1069
// Iteration #4: Calculate the average
1170
// Level 1: Array of numbers
1271
const numbersAvg = [2, 6, 9, 10, 7, 4, 1, 9];
1372

73+
function averageNumbers(arr) {
74+
75+
if (arr.length === 0) {
76+
return null;
77+
}
78+
79+
let average = sum(arr) / numbers.length;
80+
81+
return average;
82+
}
83+
1484
// Level 2: Array of strings
1585
const wordsArr = ['seat', 'correspond', 'linen', 'motif', 'hole', 'smell', 'smart', 'chaos', 'fuel', 'palace'];
1686

0 commit comments

Comments
 (0)