diff --git a/src/functions-and-arrays.js b/src/functions-and-arrays.js index 3a7dbec41..0db1d1edd 100644 --- a/src/functions-and-arrays.js +++ b/src/functions-and-arrays.js @@ -1,24 +1,74 @@ // Iteration #1: Find the maximum -function maxOfTwoNumbers() {} + +function maxOfTwoNumbers(num1, num2) { + if(num1 > num2) { + return num1; + } else { + return num2; + } +} + // Iteration #2: Find longest word -const words = ['mystery', 'brother', 'aviator', 'crocodile', 'pearl', 'orchard', 'crackpot']; -function findLongestWord() {} +function findLongestWord(wordsArray) { + if (wordsArray.length === 0) { + return null; + } + let longestWord = '' + for (i = 0; i < wordsArray.length; i++) { + let word = wordsArray[i] + if (word.length > longestWord.length) { + longestWord = word; + } + } + return longestWord; +} +const words = ['mystery', 'brother', 'aviator', 'crocodile', 'pearl', 'orchard', 'crackpot']; +console.log(findLongestWord(words)); // Iteration #3: Calculate the sum const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10]; -function sumNumbers() {} +function sumNumbers(numbersArray) { + let sum = 0 + for (let i = 0; i < numbersArray.length; i++) { + sum += numbersArray [i]; + } + return sum; +} // Iteration #3.1 Bonus: -function sum() {} +function sum(mixedValuesArr) { + if (mixedValuesArr.length === 0) { + return 0; + } + let totalOfTheMixedArray2 = 0; + + for (let i = 0; i < mixedValuesArr.length; i++) { + if (typeof mixedValuesArr[i] === 'boolean') { + if (mixedValuesArr[i] === true) { + totalOfTheMixedArray2++; + } + } + else if (typeof mixedValuesArr[i] === 'string') { + totalOfTheMixedArray2 += mixedValuesArr[i].length; + } + else if (typeof mixedValuesArr[i] === 'number') { + totalOfTheMixedArray2 += mixedValuesArr[i] + } + else { + throw new Error("The error is caused because this function only works with numbers, booleans and stings datatypes"); + } + } + return totalOfTheMixedArray2 +} @@ -26,16 +76,57 @@ function sum() {} // Level 1: Array of numbers const numbersAvg = [2, 6, 9, 10, 7, 4, 1, 9]; -function averageNumbers() {} +function averageNumbers(numbersList) { + if (numbersList.length === 0) { + return null; + } + let sum = 0; + for (let i = 0; i < numbersList.length; i++) { + sum += numbersList [i]; + } + let average = sum / numbersList.length; + + return average; +} + // Level 2: Array of strings const wordsArr = ['seat', 'correspond', 'linen', 'motif', 'hole', 'smell', 'smart', 'chaos', 'fuel', 'palace']; -function averageWordLength() { } +function averageWordLength(arrayOfWords) { + if (arrayOfWords.length === 0) { + return null; + } + let sum = 0 + for (i = 0; i