|
1 | 1 | // Iteration #1: Find the maximum
|
| 2 | +function maxOfTwoNumbers(a, b) { |
| 3 | + return Math.max(a, b); |
| 4 | +} |
2 | 5 |
|
3 | 6 | // Iteration #2: Find longest word
|
4 | 7 | const words = ['mystery', 'brother', 'aviator', 'crocodile', 'pearl', 'orchard', 'crackpot'];
|
5 | 8 |
|
| 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 | + |
6 | 24 | // Iteration #3: Calculate the sum
|
7 | 25 |
|
8 | 26 | const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10];
|
9 | 27 |
|
| 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 | + |
10 | 69 | // Iteration #4: Calculate the average
|
11 | 70 | // Level 1: Array of numbers
|
12 | 71 | const numbersAvg = [2, 6, 9, 10, 7, 4, 1, 9];
|
13 | 72 |
|
| 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 | + |
14 | 84 | // Level 2: Array of strings
|
15 | 85 | const wordsArr = ['seat', 'correspond', 'linen', 'motif', 'hole', 'smell', 'smart', 'chaos', 'fuel', 'palace'];
|
16 | 86 |
|
|
0 commit comments