diff --git a/src/functions-and-arrays.js b/src/functions-and-arrays.js index 3a7dbec41..52f419473 100644 --- a/src/functions-and-arrays.js +++ b/src/functions-and-arrays.js @@ -1,20 +1,49 @@ // Iteration #1: Find the maximum -function maxOfTwoNumbers() {} +function maxOfTwoNumbers(a, b) { + if (a > b) { + return a; + } else { + return b; + } +} // Iteration #2: Find longest word const words = ['mystery', 'brother', 'aviator', 'crocodile', 'pearl', 'orchard', 'crackpot']; -function findLongestWord() {} +function findLongestWord(word) { + if (word.length === 0) { + return null; + } + + let longestWord = word[0]; + + for (let i = 1; i < word.length; i++) { + if (word[i].length > longestWord.length) { + longestWord = word[i]; + } + } + + return longestWord; +} // Iteration #3: Calculate the sum const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10]; -function sumNumbers() {} - +function sumNumbers(numbers) { + if (numbers.length === 0) { + return 0; + } else if (numbers.length === 1) { + return numbers[0]; + } else if (numbers.includes(0)) { + return 0; + } else { + return numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); + } +} // Iteration #3.1 Bonus: @@ -26,13 +55,27 @@ function sum() {} // Level 1: Array of numbers const numbersAvg = [2, 6, 9, 10, 7, 4, 1, 9]; -function averageNumbers() {} +function averageNumbers(numbers) { + if (numbers.length === 0) { + return null; + } else if (numbers.length === 1) { + return numbers[0]; + } else { + const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); + return sum / numbers.length; + } +} // Level 2: Array of strings const wordsArr = ['seat', 'correspond', 'linen', 'motif', 'hole', 'smell', 'smart', 'chaos', 'fuel', 'palace']; -function averageWordLength() { } +function averageWordLength(words) { + if (words.length === 0) return null; + + const totalLength = words.reduce((sum, word) => sum + word.length, 0); + return totalLength / words.length; +} // Bonus - Iteration #4.1 function avg() {} @@ -52,14 +95,30 @@ const wordsUnique = [ 'bring' ]; -function uniquifyArray() {} +function uniquifyArray(array) { + if (array.length === 0) return null; + + const unique = []; + + for (let i = 0; i < array.length; i++) { + if (!unique.includes(array[i])) { + unique.push(array[i]); + } + } + + return unique; +} // Iteration #6: Find elements const wordsFind = ['machine', 'subset', 'trouble', 'starting', 'matter', 'eating', 'truth', 'disobedience']; -function doesWordExist() {} +function doesWordExist(words, wordToFind) { + if (words.length === 0) return null; + + return words.includes(wordToFind); +} @@ -78,7 +137,18 @@ const wordsCount = [ 'matter' ]; -function howManyTimes() {} +function howManyTimes(words, wordToCount) { + if (words.length === 0) return 0; + + let count = 0; + for (let i = 0; i < words.length; i++) { + if (words[i] === wordToCount) { + count++; + } + } + + return count; +}