diff --git a/Exercise/05_day_arrays.md b/Exercise/05_day_arrays.md new file mode 100644 index 0000000..a7604a9 --- /dev/null +++ b/Exercise/05_day_arrays.md @@ -0,0 +1,472 @@ +# Day 5 - Arrays + + +## [Exercise:Solutions](#exercise-solutions) + +- ### [Exercise:Level 1](#exercise-level-1) +- ### [Exercise:Level 2](#exercise-level-2) +- ### [Exercise:Level 3](#exercise-level-3)
+ + #### [Home](../README.md) | [<< Day 4](./04_day_conditional.md) | [Day 6 >>](./06_day_loops.md) + +## Exercise Solutions + +### Exercise Level 1 + + 1. Declare an empty array; + +```js +// app.js + +const arr =[]; +console.log(arr) + +``` + 2. Declare an array with more than 5 number of elements + +```js +// app.js +const arr =[1,2,3,4,5,6]; +console.log(arr) +``` + + 3. Find the length of your array + +```js +// app.js +const arr =[1,2,3,4,5,6]; +console.log(arr.length) +``` + + 4. Get the first item, the middle item and the last item of the array + +```js +// app.js +const arr =[1,2,3,4,5,6]; +console.log(arr[0]) +console.log(arr.length/2, arr.length/2+1) +console.log(arr[arr.length-1]) +``` + + 5. Declare an array called mixedDataTypes, put different data types in the array and find the length of the array. The array size should be greater than 5 + +```js +// app.js +const mixedDataTypes = [1,'nevzat',true,undefined,null, {}] +console.log(mixedDataTypes) +``` + +6. Declare an array variable name itCompanies and assign initial values Facebook, Google, Microsoft, Apple, IBM, Oracle and Amazon + +```js +// app.js +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +``` + + + 7. Print the array using console.log() + +```js +// app.js +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +console.log(itCompanies) +``` + + 8. Print the number of companies in the array + +```js +// app.js +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +console.log(itCompanies.length) +``` + + 9. Print the first company, middle and last company + +```js +//appjs + +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +console.log(itCompanies[0]) +console.log(itCompanies[Math.round(itCompanies.length/2-1)]) +console.log(itCompanies[itCompanies.length-1]) +``` + + 10. Print out each company + +```js +// app.js + +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +let result = itCompanies.forEach(countri => { + console.log(countri) +}) +``` + + 11. Change each company name to uppercase one by one and print them out + +```js +// app.js + +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +let result = itCompanies.forEach(countri => { +console.log(countri.toLocaleUpperCase()) +}) + +``` + +12. Print the array like as a sentence: Facebook, Google, Microsoft, Apple, IBM,Oracle and Amazon are big IT companies. + +```js +// app.js + +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +console.log(`${itCompanies.toString()} are big companies.`) + +``` + +13. Check if a certain company exists in the itCompanies array. If it exist return the company else return a company is not found + +```js +// app.js + +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +if(itCompanies.includes('Facebook')){ + console.log("Facebook") +} +else{ + console.log("company is not found") +} +``` + + 14. Filter out companies which have more than one 'o' without the filter method + +```js +// app.js + +const companies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +const result=[] +for(let i=0; i1){ + result.push(company) + } +} +console.log(result) +``` + 15. Sort the array using sort() method + +```js +// app.js + +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +console.log(itCompanies.sort()) + +``` + + 16. Reverse the array using reverse() method + +```js +// app.js + +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +console.log(itCompanies.reverse()) +``` + 17. Slice out the first 3 companies from the array + +```js +// app.js + +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +console.log(itCompanies.slice(0,3)) +``` + + 18. Slice out the last 3 companies from the array + +```js +// aap.js + +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +console.log(itCompanies.slice(itCompanies.length-3,itCompanies.length)) +``` + + 19. Slice out the middle IT company or companies from the array + + ```js + // app.js + + const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +console.log(itCompanies.length) //7 +console.log(itCompanies.slice(itCompanies.length/2,itCompanies.length/2+1)) +``` + + 20. Remove the first IT company from the array + +```js +// app.js + +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] + itCompanies.shift() +console.log(itCompanies) +``` + + 21. Remove the middle IT company or companies from the array + +```js +// app.js + +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +itCompanies.splice(itCompanies.length/2,1) +console.log(itCompanies) +``` +22. Remove the last IT company from the array + +```js +// app.js + +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +itCompanies.pop() +console.log(itCompanies) +``` + + 23. Remove all IT companies + +```js +// app.js + +const itCompanies = ['Facebook','Google','Microsoft','Apple','IBM','Oracle','Amazon'] +itCompanies.splice(0,itCompanies.length) +console.log(itCompanies) + +``` + +## Exercise Level 2 + + +1. Create a separate countries.js file and store the countries array in to this file, create a separate file web_techs.js and store the webTechs array in to this file. Access both file in main.js file + + +2. First remove all the punctuations and change the string to array and count the number of words in the array + +``` +let text = +'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.' +console.log(words) +console.log(words.length) +``` +``` +["I", "love", "teaching", "and", "empowering", "people", "I", "teach", "HTML", "CSS", "JS", "React", "Python"] +13 +``` +```js +// app.js + +let text = +'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.' +let noPunctuations = text.replace(/[.,]/gi) +let words = noPunctuations.split(' ') +console.log(words) +console.log(words.length) +``` + + 3. In the following shopping cart add, remove, edit items + +``` +const shoppingCart = ['Milk', 'Coffee', 'Tea', 'Honey'] + +- add 'Meat' in the beginning of your shopping cart if it has not been already added +- add Sugar at the end of you shopping cart if it has not been already added +- remove 'Honey' if you are allergic to honey +- modify Tea to 'Green Tea' +``` +```js +// app.js + +const shoppingCart = ['Milk', 'Coffee', 'Tea', 'Honey'] + +shoppingCart.unshift('meat') + +shoppingCart.push('Sugar') + +let indexHoney = shoppingCart.indexOf('Honey') // 4 +shoppingCart.splice(4,1) + +let indexTea = shoppingCart.indexOf('Tea') // 3 +shoppingCart[3] ='Green Tea' + +console.log(shoppingCart) + +``` + 4. In countries array check if 'Ethiopia' exists in the array if it exists print 'ETHIOPIA'. If it does not exist add to the countries list. + +```js +// app.js + +const countries = [ + 'Albania', + 'Bolivia', + 'Canada', + 'Denmark', + 'Ethiopia', + 'Finland', + 'Germany', + 'Hungary', + 'Ireland', + 'Japan', + 'Kenya' + ] + +let checkEthiopia = countries.includes('Ethiopia') +console.log(checkEthiopia) +``` + + 5. In the webTechs array check if Sass exists in the array and if it exists print 'Sass is a CSS preprocess'. If it does not exist add Sass to the array and print the array. + +```js +// app.js + +// const webTechs = + [ + 'HTML', + 'CSS', + 'JavaScript', + 'React', + 'Redux', + 'Node', + 'MongoDB' + ] + + let chechSass = webTechs.includes('Sass') // false + webTechs.push('Sass') + console.log(webTechs) + ``` + + + 6. Concatenate the following two variables and store it in a fullStack variable. + ``` + const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux'] +const backEnd = ['Node','Express', 'MongoDB'] + +console.log(fullStack) +``` +``` +["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"] +``` + +```js +// app.js + +const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux'] +const backEnd = ['Node','Express', 'MongoDB'] + +let fullStack = frontEnd.concat(backEnd) +console.log(fullStack) +``` + +## Exercise Level 3 + + +1. The following is an array of 10 students ages: + +``` +const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24] +``` +``` +Sort the array and find the min and max age +Find the median age(one middle item or two middle items divided by two) +Find the average age(all items divided by number of items) +Find the range of the ages(max minus min) +Compare the value of (min - average) and (max - average), use abs() method 1.Slice the first ten countries from the countries array +``` + +```js +// app.js + +let min = ages.sort() +console.log(min[0]) + + +const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24] + +let median = ages[ages.length/2] + ages[ages.length/2 -1 ]/2 +console.log(median) + + +const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24] +sum =0 + +for(const num of ages ){ +sum+=num + +} + +let average = sum/(ages.length) +console.log(average) + + +const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24] + +let arrangement = ages.sort() +let min = arrangement[0] +let max = arrangement[arrangement.length-1] +let range = max - min +console.log(range) +``` + + + 2. Find the middle country(ies) in the countries array + +```js +// app.js +const countries = [ + 'Albania', + 'Bolivia', + 'Canada', + 'Denmark', + 'Ethiopia', + 'Finland', + 'Germany', + 'Hungary', + 'Ireland', + 'Japan', + 'Kenya' + ] + + console.log(countries.length) // 11 + let middleCountry = countries[Math.ceil(countries.length/2)-1] + console.log(middleCountry) +``` + + 3. Divide the countries array into two equal arrays if it is even. If countries array is not even , one more country for the first half. + +```js +// app.js + +const countries = [ + 'Albania', + 'Bolivia', + 'Canada', + 'Denmark', + 'Ethiopia', + 'Finland', + 'Germany', + 'Hungary', + 'Ireland', + 'Japan', + 'Kenya' + ] + console.log(countries.length) // 11 not even + countries.unshift("Turkey") + let part1 = countries.splice(0,6) + let part2 = countries.splice(0,6) + console.log(part1,part2) + +``` + + #### [Home](../README.md) | [<< Day 5](./05_day_arrays.md) | [Day 7 >>](./07_day_function.md) diff --git a/Exercise/06_day_loops.md b/Exercise/06_day_loops.md new file mode 100644 index 0000000..d85b008 --- /dev/null +++ b/Exercise/06_day_loops.md @@ -0,0 +1,1074 @@ +# Day 6 - Loops + + + +## [Exercise:Solutions](#exercise-solutions) + + +- ### [Exercise:Level 1](#exercise-level-1) +- ### [Exercise:Level 2](#exercise-level-2) +- ### [Exercise:Level 3](#exercise-level-3)
+ + #### [Home](../README.md) | [<< Day 5](./05_day_arrays.md) | [Day 7 >>](./07_day_function.md) + + +## Exercise Solutions + +### Exercise Level 1 +``` +const countries = [ + 'Albania', + 'Bolivia', + 'Canada', + 'Denmark', + 'Ethiopia', + 'Finland', + 'Germany', + 'Hungary', + 'Ireland', + 'Japan', + 'Kenya' +] + +const webTechs = [ + 'HTML', + 'CSS', + 'JavaScript', + 'React', + 'Redux', + 'Node', + 'MongoDB' +] + +const mernStack = ['MongoDB', 'Express', 'React', 'Node'] +``` + +1. Iterate 0 to 10 using for loop, do the same using while and do while loop + +```js +//app.js + +for(let i= 0; i<=10; i++){ + console.log(i) +} + +let i =0; +while( i <=10){ + console.log(i) + i ++ +} + +let i= 0; +do{ + console.log(i) + i++ +} while(i<=10) + +``` + + 2. Iterate 10 to 0 using for loop, do the same using while and do while loop + +```js +// app.js + +for(let i= 10; i>=0; i--){ + console.log(i) +} + +let i =10; +while( i >=0){ + console.log(i) + i -- +} + +let i= 10; +do{ + console.log(i) + i-- +} while(i>=0) + +``` + 3. Iterate 0 to n using for loop + +```js +// app.js + +let n =5 + +for(let i=0; i<=n; i++){ + +console.log(i) +} +``` + + 4. Write a loop that makes the following pattern using console.log(): + +```js + # + ## + ### + #### + ##### + ###### + ####### +``` +```js +//app.js + +let string = "" + +for(let i=1; i<=7; i++){ + + for(let j=1; j<=i; j++){ + string+="#" + + } + console.log(string) + string+= "" +} + +``` + 5. Use loop to print the following pattern: +```js +0 x 0 = 0 +1 x 1 = 1 +2 x 2 = 4 +3 x 3 = 9 +4 x 4 = 16 +5 x 5 = 25 +6 x 6 = 36 +7 x 7 = 49 +8 x 8 = 64 +9 x 9 = 81 +10 x 10 = 100 +``` +```js + +//app.js + +const numbers =[0,1,2,3,4,5,6,7,8,9,10] + +for(num of numbers){ + console.log(`${num} * ${num} = ${num*num}`) +} + +``` + 6. Using loop print the following pattern +```js + i i^2 i^3 + 0 0 0 + 1 1 1 + 2 4 8 + 3 9 27 + 4 16 64 + 5 25 125 + 6 36 216 + 7 49 343 + 8 64 512 + 9 81 729 + 10 100 1000 + ``` +```js +//app.js + +let output = 'i i^2 i^3 \n' +for(let i=0; i<=10; i++){ + + let square =i*i; + let cube = i*i*i; + + output+= i + " "+ square + " " + cube + "\n" +} +console.log(output) +``` + + 7. Use for loop to iterate from 0 to 100 and print only even numbers + +```js + +//app.js + +for(let i=0; i<=100; i+=2){ + console.log(i) +} +``` + + 8. Use for loop to iterate from 0 to 100 and print only odd numbers + +```js +//app.js + +for(let i=1; i<=100; i+=2){ + console.log(i) +} +``` + + 9. Use for loop to iterate from 0 to 100 and print only prime numbers + 10. Use for loop to iterate from 0 to 100 and print the sum of all numbers. +``` +The sum of all numbers from 0 to 100 is 5050. +``` +```js +//app.js + +let sum = 0 +for(let i=0; i<=100; i++){ +sum+=i +} +console.log(sum) +``` + + 11. Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds. +``` +The sum of all evens from 0 to 100 is 2550. And the sum of all odds from 0 to 100 is 2500. +``` +```js +//app.js + +let sumeven = 0 +for(let i=0; i<=100; i+=2){ +sumeven+=i +} +console.log(sumeven) + + +let sumodd = 0 +for(let i=1; i<=100; i+=2){ +sumodd+=i +} +console.log(sumodd) +``` + + + 12. Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds. Print sum of evens and sum of odds as array +``` + [2550, 2500] +``` +```js +//app.js + +let sumeven = 0 +for(let i=0; i<=100; i+=2){ +sumeven+=i +} +let sumodd = 0 +for(let i=1; i<=100; i+=2){ +sumodd+=i +} +let arr = [sumeven,sumodd] +console.log(arr) +``` + + 13. Develop a small script which generate array of 5 random numbers + +```js +//app.js + +outPut = '' +for(let i =0; i<5; i++){ + outPut+= Math.floor(Math.random(i)*10) +} +console.log(outPut) +``` + + + 14. Develop a small script which generate array of 5 random numbers and the numbers must be unique + +```js +//app.js + +let arr = [] +while(arr.length<5){ + randomNum = Math.floor(Math.random() * 10) + if(!arr.includes(randomNum)){ + arr.push(randomNum) + } +} +console.log(arr.toString()) +``` + +15. Develop a small script which generate a six characters random id: +``` +5j2khz +``` +```js +//app.js + +let text = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' +let randomCharecters = '' +for (let i = 0; i < 6; i++) { + let index = Math.floor(Math.random() * text.length) + randomCharecters += text[index] +} +console.log(randomCharecters) +``` + + +## Exercise Level 2 + + + 1. Develop a small script which generate any number of characters random id: +``` + fe3jo1gl124g +``` +```js +//app.js + +let text = 'A1B2C3D4E5F6G7H8I9J0KLMN1O2P3Q4R5S6T7UV8W9XYZabcdefghijklmnopqrstuvwxyz' +let randomCharecters = '' + +let index = Math.floor(Math.random() * text.length) + +for (let i = 0; i < index; i++) { + + let a = Math.floor(Math.random()*i) + randomCharecters += text[a] +} +console.log(randomCharecters) +``` + + 2. Write a script which generates a random hexadecimal number. +``` +'#ee33df' +``` +```js +//app.js + +let hexzaArr = ['a','b','c','d','e','f',1,2,3,4,5,6,7,8,9,0] + +let hexzaNumber = '#' + + + for(let i=1; i<=hexzaArr.length; i++){ + let index = hexzaArr[Math.floor(Math.random() * hexzaArr.length)] + + hexzaNumber += index + + if(hexzaNumber.length==7){ + break; + } + } + console.log(hexzaNumber) + ``` + + + 3. Write a script which generates a random rgb color number +``` +rgb(240,180,80) +``` +```js +//app.js + +let number1 = Math.floor(Math.random()*256) +let number2 = Math.floor(Math.random()*256) +let number3 = Math.floor(Math.random()*256) + +console.log(`rgb(${number1},${number2},${number3})`) +``` + + 4. Using the above countries array, create the following new array. +``` +["ALBANIA", "BOLIVIA", "CANADA", "DENMARK", "ETHIOPIA", "FINLAND", "GERMANY", "HUNGARY", "IRELAND", "JAPAN", "KENYA"] +``` +```js +//app.js + +newArr = [] +for(const country of countries){ + newArr.push(country.toLocaleUpperCase()) +} +console.log(newArr) +``` + + 5. Using the above countries array, create an array for countries length +``` +[7, 7, 6, 7, 8, 7, 7, 7, 7, 5, 5] +``` +```js +//app.js + +const countries = [ + 'Albania', + 'Bolivia', + 'Canada', + 'Denmark', + 'Ethiopia', + 'Finland', + 'Germany', + 'Hungary', + 'Ireland', + 'Japan', + 'Kenya' + ] + let arr = [] + for(let i=0; i count.length){ + + count = arr[i] + } +} +console.log(count) +``` + + + 10. Using the above countries array, find the country containing only 5 characters. +``` +['Japan', 'Kenya'] +``` +```js +//app.js +const countries = [ + 'Albania', + 'Bolivia', + 'Canada', + 'Denmark', + 'Ethiopia', + 'Finland', + 'Germany', + 'Hungary', + 'Ireland', + 'Japan', + 'Kenya' + ] + let newArr = [] + for(const country of countries){ + if(country.length==5){ + newArr.push(country) + } + } + console.log(newArr) +``` + + 11. Find the longest word in the webTechs array + +```js +//app.js + +const webTechs = [ + 'HTML', + 'CSS', + 'JavaScript', + 'React', + 'Redux', + 'Node', + 'MongoDB' + ] + let longWorld = '' + + for(let tech of webTechs){ +if(tech.length>longWorld.length){ + longWorld = tech +} + } + console.log(longWorld) +``` +12. Use the webTechs array to create the following array of arrays: +``` +[["HTML", 4], ["CSS", 3],["JavaScript", 10],["React", 5],["Redux", 5],["Node", 4],["MongoDB", 7]] +``` +```js +//app.js + +const webTechs = [ + 'HTML', + 'CSS', + 'JavaScript', + 'React', + 'Redux', + 'Node', + 'MongoDB' + ] + + let arr = [] + for( let tech of webTechs){ + arr.push(`${tech},${tech.length}`) + } + console.log(arr) +``` + +13. An application created using MongoDB, Express, React and Node is called a MERN stack app. Create the acronym MERN by using the array mernStack + +```js +//app.js + +const skills = ['MongoDB', 'Express','React', 'Node'] + +let mern = ''; +for(let i=0; i=0; i--){ +reverseFruit.push(fruit[i]) +} +console.log(reverseFruit) +``` + + 16. Print all the elements of array as shown below. +``` + const fullStack = [ + ['HTML', 'CSS', 'JS', 'React'], + ['Node', 'Express', 'MongoDB'] + ] +``` +``` + HTML + CSS + JS + REACT + NODE + EXPRESS + MONGODB +``` +```js +//app.js +const fullStack = [ + ['HTML', 'CSS', 'JS', 'React'], + ['Node', 'Express', 'MongoDB'] + ] + const merger =fullStack[0].concat(fullStack[1]) + for(const skills of merger){ + console.log(skills) + } + +``` +## Exercise Level 3 + + +1. Copy countries array(Avoid mutation) + + +```js +//app.js + +const countries = [ + 'Albania', + 'Bolivia', + 'Canada', + 'Denmark', + 'Ethiopia', + 'Finland', + 'Germany', + 'Hungary', + 'Ireland', + 'Japan', + 'Kenya' + ] + const newCountries = countries.slice() + console.log(newCountries) +``` + + + + 2. Arrays are mutable. Create a copy of array which does not modify the original. Sort the copied array and store in a variable sortedCountries +```js +//app.js + +const countries = [ + 'Albania', + 'Bolivia', + 'Canada', + 'Denmark', + 'Ethiopia', + 'Finland', + 'Germany', + 'Hungary', + 'Ireland', + 'Japan', + 'Kenya' + ] + const sorCountries = countries.slice() + console.log(sorCountries.sort()) +``` + + + + 3. Sort the webTechs array and mernStack array + +```js +//app.js + +const webTechs = [ + 'HTML', + 'CSS', + 'JavaScript', + 'React', + 'Redux', + 'Node', + 'MongoDB' + ] + const mernStack = ['MongoDB', 'Express', 'React', 'Node'] + mernStack.sort() + webTechs.sort() + console.log(webTechs,mernStack) +``` + + + +4. Extract all the countries contain the word 'land' from the countries array and print it as array +```js +//app.js + +const countries = [ + 'Albania', + 'Bolivia', + 'Canada', + 'Denmark', + 'Ethiopia', + 'Finland', + 'Germany', + 'Hungary', + 'Ireland', + 'Japan', + 'Kenya' + ] +let newArr = [] +countries.forEach(function(countri){ +if(countri.includes('land')){ + newArr.push(countri) +} +} +) +console.log(newArr) +``` + + + + 5. Find the country containing the hightest number of characters in the countries array + +```js +//app.js + +const arr = [ + 'Albania', + 'Bolivia', + 'Canada', + 'Denmark', + 'Ethiopia', + 'Finland', + 'Germany', + 'Hungary', + 'Ireland', + 'Japan', + 'Kenya' + ] + let count = ''; + +for(let i = 0; i count.length){ + + count = arr[i] + } +} +console.log(count) +``` + + + +6. Extract all the countries contain the word 'land' from the countries array and print it as array +```js +//app.js + +const countries = [ + 'Afghanistan', + 'Albania', + 'Algeria', + 'Andorra', + 'Angola', + 'Antigua and Barbuda', + 'Argentina', + 'Armenia', + 'Australia', + 'Austria', + 'Azerbaijan', + 'Bahamas', + 'Bahrain', + 'Bangladesh', + 'Barbados', + 'Belarus', + 'Belgium', + 'Belize', + 'Benin', + 'Bhutan', + 'Bolivia', + 'Bosnia and Herzegovina', + 'Botswana', + 'Brazil', + 'Brunei', + 'Bulgaria', + 'Burkina Faso', + 'Burundi', + 'Cambodia', + 'Cameroon', + 'Canada', + 'Cape Verde', + 'Central African Republic', + 'Chad', + 'Chile', + 'China', + 'Colombi', + 'Comoros', + 'Congo (Brazzaville)', + 'Congo', + 'Costa Rica', + "Cote d'Ivoire", + 'Croatia', + 'Cuba', + 'Cyprus', + 'Czech Republic', + 'Denmark', + 'Djibouti', + 'Dominica', + 'Dominican Republic', + 'East Timor (Timor Timur)', + 'Ecuador', + 'Egypt', + 'El Salvador', + 'Equatorial Guinea', + 'Eritrea', + 'Estonia', + 'Ethiopia', + 'Fiji', + 'Finland', + 'France', + 'Gabon', + 'Gambia, The', + 'Georgia', + 'Germany', + 'Ghana', + 'Greece', + 'Grenada', + 'Guatemala', + 'Guinea', + 'Guinea-Bissau', + 'Guyana', + 'Haiti', + 'Honduras', + 'Hungary', + 'Iceland', + 'India', + 'Indonesia', + 'Iran', + 'Iraq', + 'Ireland', + 'Israel', + 'Italy', + 'Jamaica', + 'Japan', + 'Jordan', + 'Kazakhstan', + 'Kenya', + 'Kiribati', + 'Korea, North', + 'Korea, South', + 'Kuwait', + 'Kyrgyzstan', + 'Laos', + 'Latvia', + 'Lebanon', + 'Lesotho', + 'Liberia', + 'Libya', + 'Liechtenstein', + 'Lithuania', + 'Luxembourg', + 'Macedonia', + 'Madagascar', + 'Malawi', + 'Malaysia', + 'Maldives', + 'Mali', + 'Malta', + 'Marshall Islands', + 'Mauritania', + 'Mauritius', + 'Mexico', + 'Micronesia', + 'Moldova', + 'Monaco', + 'Mongolia', + 'Morocco', + 'Mozambique', + 'Myanmar', + 'Namibia', + 'Nauru', + 'Nepal', + 'Netherlands', + 'New Zealand', + 'Nicaragua', + 'Niger', + 'Nigeria', + 'Norway', + 'Oman', + 'Pakistan', + 'Palau', + 'Panama', + 'Papua New Guinea', + 'Paraguay', + 'Peru', + 'Philippines', + 'Poland', + 'Portugal', + 'Qatar', + 'Romania', + 'Russia', + 'Rwanda', + 'Saint Kitts and Nevis', + 'Saint Lucia', + 'Saint Vincent', + 'Samoa', + 'San Marino', + 'Sao Tome and Principe', + 'Saudi Arabia', + 'Senegal', + 'Serbia and Montenegro', + 'Seychelles', + 'Sierra Leone', + 'Singapore', + 'Slovakia', + 'Slovenia', + 'Solomon Islands', + 'Somalia', + 'South Africa', + 'Spain', + 'Sri Lanka', + 'Sudan', + 'Suriname', + 'Swaziland', + 'Sweden', + 'Switzerland', + 'Syria', + 'Taiwan', + 'Tajikistan', + 'Tanzania', + 'ThailanD', + 'Togo', + 'Tonga', + 'Trinidad and Tobago', + 'Tunisia', + 'Turkey', + 'Turkmenistan', + 'Tuvalu', + 'Uganda', + 'Ukraine', + 'United Arab Emirates', + 'United Kingdom', + 'United States', + 'Uruguay', + 'Uzbekistan', + 'Vanuatu', + 'Vatican City', + 'Venezuela', + 'Vietnam', + 'Yemen', + 'Zambia', + 'Zimbabwe' + ] + let outPut = [] + for(let country of countries){ + if(country.toLowerCase().includes('land')){ + outPut.push(country) + } + } + console.log(outPut) + +``` + + + + + 7. Extract all the countries containing only four characters from the countries array and print it as array +```js +//app.js + + let outPut = [] + for(let country of countries){ + if(country.length == 4){ + outPut.push(country) + } + } + console.log(outPut) +``` + + + + 8. Extract all the countries containing two or more words from the countries array and print it as array +```js +//app.js + +let result = [] + for(let country of countries){ + if(country.includes(" ")){ + result.push(country) + + } + } + console.log(result) +``` + + + + 9. Reverse the countries array and capitalize each country and stored it as an array + + ```js +//app.js + +let result = [] +let newArr = countries.reverse() + + for(let country of newArr){ + result.push(country.toLocaleUpperCase()) + } + console.log(result) +``` + + #### [Home](../README.md) | [<< Day 5](./05_day_arrays.md) | [Day 7 >>](./07_day_function.md) diff --git a/Exercise/07_day_function.md b/Exercise/07_day_function.md new file mode 100644 index 0000000..6ddc432 --- /dev/null +++ b/Exercise/07_day_function.md @@ -0,0 +1,950 @@ +# Day 7 - Functions + + +## [Exercise:Solutions](#exercise-solutions) + +- ### [Exercise:Level 1](#exercise-level-1) +- ### [Exercise:Level 2](#exercise-level-2) +- ### [Exercise:Level 3](#exercise-level-3)
+ + #### [Home](../README.md) | [<< Day 6](./06_day_loops.md) | [Day 8 >>](./08_day_object.md) + + +## Exercise Solutions + +### Exercise Level 1 + +1. Declare a function fullName and it print out your full name. + +```js +//app.js + +function fullName(){ + console.log("nevzat atalay") +} +fullName() + +``` + +2. Declare a function fullName and now it takes firstName, lastName as a parameter and it returns your full - name. +```js +//app.js + +function fullName(name,lastname){ + let str=" " + console.log(name + str + lastname) +} +fullName('nevzat','atalay') +``` + + + 3. Declare a function addNumbers and it takes two two parameters and it returns sum. +```js +//app.js + +function addNumbers(num1,num2){ + let sum =0 + sum += num1 + num2 + return sum +} +console.log(addNumbers(7,8)) +``` + + +4. An area of a rectangle is calculated as follows: area = length x width. Write a function which calculates areaOfRectangle. +```js +//app.js + +function areaOfRengle(width,length){ + area = width * length + return area +} +console.log(areaOfRengle(7,8)) +``` + + +5. A perimeter of a rectangle is calculated as follows: perimeter= 2x(length + width). Write a function which calculates perimeterOfRectangle. +```js +//app.js + +function perimeterOfRengle(width,length){ + perimeter = 2 * (width + length) + return perimeter +} +console.log(perimeterOfRengle(7,8)) +``` + + +6. A volume of a rectangular prism is calculated as follows: volume = length x width x height. Write a function which calculates volumeOfRectPrism. +```js +//app.js + +function volumeOfRengle(width,length,height){ + volume = width * length *height + return volume +} +console.log(volumeOfRengle(7,8,9)) +``` + + + 7. Area of a circle is calculated as follows: area = π x r x r. Write a function which calculates areaOfCircle +```js +//app.js + +function areaCircle(r){ + area = Math.floor(Math.PI)*r*r + return area +} +console.log(areaCircle(3)) +``` + + +8. Circumference of a circle is calculated as follows: circumference = 2πr. Write a function which calculates circumOfCircle +```js +//app.js + +function ferenceCircle(r){ + ference = 2 * Math.floor(Math.PI)*r + return ference +} +console.log(ferenceCircle(3)) +``` + + +9. Density of a substance is calculated as follows:density= mass/volume. Write a function which calculates density. +```js +//app.js + +function densitySubtance(mass,volume){ + density = mass/volume + return volume +} +console.log(densitySubtance(10,2)) +``` + + + 10. Speed is calculated by dividing the total distance covered by a moving object divided by the total amount of time taken. Write a function which calculates a speed of a moving object, speed. +```js +//app.js + +function speedDivid(distance,time){ + + speed = distance/time + return speed +} +console.log(speedDivid(100,2)) +``` + + +11. Weight of a substance is calculated as follows: weight = mass x gravity. Write a function which calculates weight. +```js +//app.js + +function weightSubtance(mass,gravity){ + weight = mass * gravity + return weight +} +console.log(weightSubtance(5,10)) +``` + + + 12. Temperature in oC can be converted to oF using this formula: oF = (oC x 9/5) + 32. Write a function which convert oC to oF convertCelsiusToFahrenheit. +```js +//app.js + +function convertCelciusToFahrenheit(celcius){ + fahrenheit = (celcius * 9/5) + 32 +return fahrenheit +} +console.log(convertCelciusToFahrenheit(1)) +``` + + + 13. Body mass index(BMI) is calculated as follows: bmi = weight in Kg / (height x height) in m2. Write a function which calculates bmi. BMI is used to broadly define different weight groups in adults 20 years old or older.Check if a person is underweight, normal, overweight or obese based the information given below. +``` +- The same groups apply to both men and women. +- Underweight: BMI is less than 18.5 +- Normal weight: BMI is 18.5 to 24.9 +- Overweight: BMI is 25 to 29.9 +- Obese: BMI is 30 or more +``` +```js +//app.js + +function bmiPeople(weight,height,){ + + bmi = weight/(height*height) +if(bmi <=18.5){ + console.log('Underweight') + return +} +else if(bmi >=18.5 && bmi <=24.9 ){ + console.log('Normal weight') + return + +} +else if(bmi >= 25 && bmi <=29.9){ + console.log('Overweight') + return +} +else if(bmi >=30){ + console.log('Obese') + return +} +else{ + console.log('letfen degerlerinizikontrol ediniz') +} +} +bmiPeople(100,1.54) +``` + + +14. Write a function called checkSeason, it takes a month parameter and returns the season:Autumn, Winter, Spring or Summer. +```js +//app.js + +function checkSeason(mount){ + if(mount=='september' || mount=='november' ||mount=='october' ){ + console.log('season is Autum') + } + else if(mount=='december' || mount=='january' ||mount=='february' ){ + console.log('season is winter') + } + else if(mount=='march' || mount=='may' ||mount=='april' ){ + console.log('season is spring') + } +} +checkSeason('september') +``` + + + 15. Math.max returns its largest argument. Write a function findMax that takes three arguments and returns their maximum with out using Math.max method. +``` +console.log(findMax(0, 10, 5)) +10 +console.log(findMax(0, -10, -2)) +0 +``` + +```js +//app.js +function findMaxNumber(a,b,c){ + + maxnumber = Math.max(a,b,c) + return maxnumber +} +console.log(findMaxNumber(3,5,7)) +``` + +## Exercise Level 2 + + 1. Linear equation is calculated as follows: ax + by + c = 0. Write a function which calculates value of a linear equation, solveLinEquation. +```js +//app.js + +function solveLinEquation(a, b, c, x) { + // ax + by + c = 0 denkleminde x değeri verildiğinde y değerini hesaplar + // y = (-c - ax) / b formülünü kullanır + // a, b, c, x sayısal değerler olmalıdır + // b sıfır olmamalıdır + // y değeri sayısal olarak döndürülür + if (b === 0) { + throw new Error("b değeri sıfır olamaz"); + } + let y = (-c - a * x) / b; + return y; +} +let a = solveLinEquation(3,5,7,8) + +console.log(a) +``` + + + 2. Quadratic equation is calculated as follows: ax2 + bx + c = 0. Write a function which calculates value or values of a quadratic equation, solveQuadEquation. +``` +console.log(solveQuadratic()) // {0} +console.log(solveQuadratic(1, 4, 4)) // {-2} +console.log(solveQuadratic(1, -1, -2)) // {2, -1} +console.log(solveQuadratic(1, 7, 12)) // {-3, -4} +console.log(solveQuadratic(1, 0, -4)) //{2, -2} +console.log(solveQuadratic(1, -1, 0)) //{1, 0} +``` +```js +//app.js + +// solventQuadEquation fonksiyonu tanımlanıyor +function solventQuadEquation(a, b, c) { + // diskriminant hesaplanıyor + let d = b * b - 4 * a * c; + // diskriminantın sıfırdan büyük veya eşit olup olmadığı kontrol ediliyor + if (d >= 0) { + // diskriminantın karekökü alınıyor + let sqrt_d = Math.sqrt(d); + // denklemin kökleri hesaplanıyor + let x1 = (-b + sqrt_d) / (2 * a); + let x2 = (-b - sqrt_d) / (2 * a); + // kökleri bir dizi olarak döndürüyor + return [x1, x2]; + } else { + // diskriminant negatif ise, hata mesajı döndürüyor + return "Denklemin gerçek kökü yoktur."; + } +} + +// denklemin katsayıları +let a = 1; +let b = -5; +let c = 6; + +// fonksiyon çağrılıyor ve sonucu yazdırılıyor +console.log(solventQuadEquation(a, b, c)); + +``` + + 3. Declare a function name printArray. It takes array as a parameter and it prints out each value of the array. +```js +//app.js + +const arr = [1,2,3,4,5,6,7] + +function printArr(){ + for(const num of arr){ + console.log(num) + } +} +printArr(arr) +``` + + +4. Write a function name showDateTime which shows time in this format: 08/01/2020 04:08 using the Date object. +``` +showDateTime() +08/01/2020 04:08 +``` +```js +//app.js + +function showDateTime(){ + + let now = new Date(); + +let day = now.getDate() +let mount = now.getMonth() +1 +let year = now.getFullYear() +let hours = now.getHours() +let minut = now.getMinutes() + +if(day<10){ + day = '0'+ day +} +if(mount<10){ + mount = '0' + mount +} +if(hours<10){ + hours = '0' + hours +} +if(minut<10){ + minut = '0' + minut +} + +return console.log(`${day}/${mount}/${year} ${hours}:${minut} `) + +} +showDateTime() + +``` + + +5. Declare a function name swapValues. This function swaps value of x to y. +``` +swapValues(3, 4) // x => 4, y=>3 +swapValues(4, 5) // x = 5, y = 4 +``` +```js +//app.js + +function swapValue(x,y){ + + let changeX = y + let changeY = x + return console.log(`${changeX},${changeY}`)} + swapValue(5,4) + +``` + + 6. Declare a function name reverseArray. It takes array as a parameter and it returns the reverse of the array (don't use method). +``` +console.log(reverseArray([1, 2, 3, 4, 5])) +//[5, 4, 3, 2, 1] +console.log(reverseArray(['A', 'B', 'C'])) +//['C', 'B', 'A'] +``` +```js +//app.js + +const arr = [1,2,3,4,5,6,7] + +function reverseArr(){ + return console.log(arr.reverse()) +} +reverseArr(arr) +``` + + + 7. Declare a function name capitalizeArray. It takes array as a parameter and it returns the - capitalizedarray. +```js +//app.js + +const arr = ['nevzat', 'atalay', 'bitlis'] + +arr.forEach(word => { + console.log( word.toUpperCase()) +}) +``` + + + 8. Declare a function name addItem. It takes an item parameter and it returns an array after adding the item +```js +//app.js + +function addItem(text){ + arr = text.split(" ") + return arr + } + console.log(addItem('Nevzat Atalay Bitlis')) +``` + + + 9. Declare a function name removeItem. It takes an index parameter and it returns an array after removing an item +```js +//app.js + +function removeItem(index) { + array = [1,2,3,4,5,6,7,8,9] + assume the array is defined globally + var newArray = array.slice(); // make a copy of the array + newArray.splice(index, 2); // remove the item at the given index + return newArray; // return the new array + } + console.log(removeItem(2)) +``` + + + 10. Declare a function name sumOfNumbers. It takes a number parameter and it adds all the numbers in that range. +```js +//app.js + +function sumOfNumbers(number){ + + let sum = 0; + for(let i=1; i<=number; i++){ + sum += i; + } + return sum; +} +console.log(sumOfNumbers(5)); +``` + + +11. Declare a function name sumOfOdds. It takes a number parameter and it adds all the odd numbers in that - range. +```js +//app.js + +function sumOfOddNumbers(number){ + + let sum = 0; + for(let i=1; i<=number; i+=2){ + sum += i; + } + return sum; +} +console.log(sumOfOddNumbers(4)); +``` + + + +12. Declare a function name sumOfEven. It takes a number parameter and it adds all the even numbers in that - range. +```js +//app.js + +function sumOfEvenNumbers(number){ + + let sum = 0; + for(let i=0; i<=number; i+=2){ + sum += i; + } + return sum; +} +console.log(sumOfEvenNumbers(4)); +``` + + +13. parameter and it counts number of evens and odds in the number. +``` +evensAndOdds(100); +The number of odds are 50. +The number of evens are 51. +``` +```js +//app.js + +eventsAndOdds(100) + +function eventsAndOdds(number){ + + let event=0 + let odd = 0 + for(let i =0; i<=number; i++){ + if(i%2 ==0){ + event = event +1 + } + else{ + odd = odd +1 + } + } + console.log(`Number is includes ${event} event and ${odd} odd number`) +} + +``` + +14. Write a function which takes any number of arguments and return the sum of the arguments +``` +sum(1, 2, 3) // -> 6 +sum(1, 2, 3, 4) // -> 10 +``` +```js +//app.js + +function sumNumbers(number1,number2,number3){ + let sum = number1+number2+number3 + + return console.log(sum) + } + sumNumbers(1,2,3,) +``` + + + 15. Writ a function which generates a randomUserIp. +```js +//app.js + +function getRandomInt(min, max) { + return Math.floor(Math.random() * (max - min + 1)) + min; + } + + function randomUserIp(){ + const ip = [getRandomInt(0,255),getRandomInt(0,255),getRandomInt(0,255),getRandomInt(0,255)] + return ip.join('.') + } + console.log(randomUserIp()) + +``` + + + 16. Write a function which generates a randomMacAddress + +```js +//app.js + +function getRandomHex(){ + const arr = ['0',"1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"] + return arr[Math.floor(Math.random()*arr.length)] + } + + function randomMacAdres(){ + + const mac = [getRandomHex() + getRandomHex(), getRandomHex() + getRandomHex(), getRandomHex() + getRandomHex(), getRandomHex() + getRandomHex(), getRandomHex() + getRandomHex(), getRandomHex() + getRandomHex(), getRandomHex() + getRandomHex(), getRandomHex() + getRandomHex() + + ] + return mac.join(':') + } + console.log(randomMacAdres()) + ``` + + +17. Declare a function name randomHexaNumberGenerator. When this function is called it generates a random hexadecimal number. The function return the hexadecimal number. +``` +console.log(randomHexaNumberGenerator()); +'#ee33df' +``` +```js +//app.js + +function ranfomHexzadecimal(){ + let text = '0123456789ABCDEF' + let hex = '#' + for(let i=0; i<6; i++){ + let index = Math.floor(Math.random()*text.length) + hex += text[index] + } + return hex + } + + console.log(ranfomHexzadecimal()) + ``` + +18. Declare a function name userIdGenerator. When this function is called it generates seven character id. The function return the id. +``` +console.log(userIdGenerator()); +41XTDbE +``` +```js +//app.js + +function userIdGenerator(){ + let text = '0123456789ABCDEFGHJKLMNOPRSŞTOVYZabcdefghojklmnprsştvyz' + let id = '' + for(let i=0; i<7; i++){ + let index = Math.floor(Math.random()*text.length) + id += text[index] + } + return id + } + console.log(userIdGenerator()) +``` + +## Exercise Level 3 + +1. Modify the userIdGenerator function. Declare a function name userIdGeneratedByUser. It doesn’t take any parameter but it takes two inputs using prompt(). One of the input is the number of characters and the second input is the number of ids which are supposed to be generated. + +```js +// app.js + +let charecter = prompt("Kaç karekterli id istiyorsunuz"); +let piece = prompt("kaç adet id istiyorsunuz"); + +function userIdGeneratedByUser() { + let str = "1234567890abcdefghıijklmnoöprsştyüvyz"; + let id = ""; + + for (let i = 0; i <= charecter; i++) { + id += str[Math.floor(Math.random() * str.length)]; + } + + console.log(id); +} + +callingUserIdGeneratedByUser(piece); + +function callingUserIdGeneratedByUser(n) { + for (let i = 0; i < n; i++) { + userIdGeneratedByUser(); + } +} +``` +2. Write a function name rgbColorGenerator and it generates rgb colors. + + +```js +// app.js + +function rgbColor(){ + let randomNumber1 = Math.floor(Math.random() * 255) + let randomNumber2 = Math.floor(Math.random() * 255) + let randomNumber3 = Math.floor(Math.random() * 255) + + return `rgb(${randomNumber1},${randomNumber2},${randomNumber3})` + +} +console.log(rgbColor()) +``` + +3. Write a function arrayOfHexaColors which return any number of hexadecimal colors in an array. + +```js +// app.js + + +const array = [1,2,3,4,5,6,7,8,9,0,"A","B","C","D","E","F"] + +function arrayOfHexaColors(n){ + let hexaColor = "#" + + for(let i=0; i<6; i++){ + hexaColor+= n[Math.floor(Math.random()*n.length)] + } + + return console.log(hexaColor) +} + +arrayOfHexaColors(array) +``` +4. Write a function arrayOfRgbColors which return any number of RGB colors in an array. + + ```js +// app.js + +function arrayOfRgbColors(num) { + const colors = []; + for (let i = 0; i < num; i++) { + const r = Math.floor(Math.random() * 256); + const g = Math.floor(Math.random() * 256); + const b = Math.floor(Math.random() * 256); + colors.push(`rgb(${r}, ${g}, ${b})`); + } + return colors; + } + +``` +5. Write a function convertHexaToRgb which converts hexa color to rgb and it returns an rgb color. + + ```js +// app.js + +function convertHexaToRgb(hex) { + const r = parseInt(hex.substring(1, 3), 16); + const g = parseInt(hex.substring(3, 5), 16); + const b = parseInt(hex.substring(5, 7), 16); + return `rgb(${r}, ${g}, ${b})`; + } + + srt="#34f354" + + console.log(convertHexaToRgb(srt)) + + +``` +6. Write a function convertRgbToHexa which converts rgb to hexa color and it returns an hexa color. + + ```js +// app.js + + function convertRgbToHexa(r, g, b) { + const hexR = r.toString(16).padStart(2, "0"); + const hexG = g.toString(16).padStart(2, "0"); + const hexB = b.toString(16).padStart(2, "0"); + return `#${hexR}${hexG}${hexB}`; + } +``` + +7. Write a function generateColors which can generate any number of hexa or rgb colors. + + + + ```js +// app.js + +function rgbColor(){ + let randomNumber1 = Math.floor(Math.random() * 255) + let randomNumber2 = Math.floor(Math.random() * 255) + let randomNumber3 = Math.floor(Math.random() * 255) + + return console.log(`rgb(${randomNumber1},${randomNumber2},${randomNumber3})`) + +} + + +function arrayOfHexaColors(){ + const array = [1,2,3,4,5,6,7,8,9,0,"A","B","C","D","E","F"] + + let hexaColor = "#" + + for(let i=0; i<6; i++){ + hexaColor+= array[Math.floor(Math.random()*array.length)] + } + + return console.log(hexaColor) +} + +function generateColors(color,number){ + + if(color=="hexa"){ + for(let i =0; i 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [array[i], array[j]] = [array[j], array[i]]; + } + return array; + } + console.log( shuffleArray(array) ) +``` +9. + +```js +// app.js + +function factorial(num) { + if (num < 0) { + return -1; + } else if (num == 0) { + return 1; + } else { + return (num * factorial(num - 1)); + } + } + + console.log(factorial(5)) +``` +10. Call your function isEmpty, it takes a parameter and it checks if it is empty or not + +```js +// app.js +function isEmpty(variable) { + if (variable === null || variable === undefined) { + return true; + } else if (typeof variable === 'string' && variable.trim().length === 0) { + return true; + } else if (Array.isArray(variable) && variable.length === 0) { + return true; + } else if (typeof variable === 'object' && Object.keys(variable).length === 0) { + return true; + } else { + return false; + } +} +``` +11. Call your function sum, it takes any number of arguments and it returns the sum. + + +```js +// app.js + +function sum(...args) { + return args.reduce((a, b) => a + b, 0); +} +``` +12. Write a function called sumOfArrayItems, it takes an array parameter and return the sum of all the items. Check if all the array items are number types. If not give return reasonable feedback. + +```js +// app.js +function sumOfArrayItems(arr) { + if (!Array.isArray(arr)) { + return "Error: The input is not an array."; + } else if (arr.length === 0) { + return "Error: The array is empty."; + } else if (arr.some(isNaN)) { + return "Error: The array contains non-numeric elements."; + } else { + return arr.reduce((a, b) => a + b, 0); + } +} +``` +13. Write a function called average, it takes an array parameter and returns the average of the items. Check if all the array items are number types. If not give return reasonable feedback. + +```js +// app.js +function average(arr) { + let sum = 0; + let count = 0; + for (let i = 0; i < arr.length; i++) { + if (typeof arr[i] !== "number") { + return "Error: All elements of the array must be numbers."; + } + sum += arr[i]; + count++; + } + return sum / count; + } + +``` +14. Write a function called modifyArray takes array as parameter and modifies the fifth item of the array and return the array. If the array length is less than five it return 'item not found'. + +```js +// app.js +function modifyArray(arr) { + if (arr.length < 5) { + return 'item not found'; + } + arr[4] = 'modified'; + return arr; + } +``` +15. Write a function called isPrime, which checks if a number is prime number. + + +```js +// app.js +function isPrime(num) { + if (num <= 1) { + return false; + } + for (let i = 2; i <= Math.sqrt(num); i++) { + if (num % i === 0) { + return false; + } + } + return true; +} + +``` +16. Write a functions which checks if all items are unique in the array. + +```js +// app.js +function areAllItemsUnique(arr) { + return new Set(arr).size === arr.length; + } + + const hey = [1,2,4,4] + console.log(areAllItemsUnique(hey)) +``` +17. +```js +// app.js +function areAllItemsSameType(arr) { + if (arr.length === 0) { + return true; + } + const firstType = typeof arr[0]; + return arr.every((item) => typeof item === firstType); + } + + const array = [1,2,null,4,5] + console.log(areAllItemsSameType(array)) +``` +18. JavaScript variable name does not support special characters or symbols except $ or _. Write a function isValidVariable which check if a variable is valid or invalid variable. + + +```js +// app.js +function isValidVariable(variableName) { + const regex = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/; + return regex.test(variableName); + } +``` +19. Write a function which returns array of seven random numbers in a range of 0-9. All the numbers must be unique. +``` +sevenRandomNumbers() +[(1, 4, 5, 7, 9, 8, 0)] +``` + +```js +// app.js +function getUniqueRandomNumbers() { + const numbers = new Set(); + while (numbers.size < 7) { + numbers.add(Math.floor(Math.random() * 10)); + } + return Array.from(numbers); +} + +``` +20. Write a function called reverseCountries, it takes countries array and first it copy the array and returns the reverse of the original array + + +```js +// app.js +function reverseCountries(countries) { + const copy = countries.slice(); + return copy.reverse(); +} +``` diff --git a/Exercise/08_day_object.md b/Exercise/08_day_object.md new file mode 100644 index 0000000..e4f3250 --- /dev/null +++ b/Exercise/08_day_object.md @@ -0,0 +1,348 @@ + +# Day 7 - Functions + + +## [Exercise:Solutions](#exercise-solutions) + +- ### [Exercise:Level 1](#exercises-level-1) +- ### [Exercise:Level 2](#exercises-level-2) +- ### [Exercise:Level 3](#exercises-level-3)
+ + #### [Home](../README.md) | [<< Day 6](./06_day_loops.md) | [Day 8 >>](./08_day_object.md) + + +## Exercise Solutions + +### Exercises Level 1 + + 1. Create an empty object called dog + +```js +//app.js +dog = {} +``` +2. Print the the dog object on the console + +```js +//app.js + +dog = {} +console.log(dog) +``` + + + 3. Add name, legs, color, age and bark properties for the dog object. The bark property is a method which return woof woof +```js +//app.js + +dog = { + name:'garip', + legs:4, + age:6, + color:'black', + bark:'woof woof' + } + console.log(dog) +``` + + + 4. Get name, legs, color, age and bark value from the dog object +```js +//app.js + +dog = { + name:'garip', + legs:4, + age:6, + color:'black', + bark:'woof woof' + } +console.log(dog.name) +console.log(dog.legs) +console.log(dog['age']) +console.log(dog['color']) +console.log(dog['bark']) +``` + + 5. Set new properties the dog object: breed, getDogInfo +```js +//app.js + +dog = { + name:'garip', + legs:4, + age:6, + color:'black', + bark:'woof woof' + } +dog.breed = 'kangal' +console.log(dog.breed) +``` + +### Exercises Level 2 + +1. Find the person who has many skills in the users object. + +```js +//app.js + let maxSkills = 0; +let mostSkilledUser = ""; +for (let user in users) { + if (users[user].skills.length > maxSkills) { + maxSkills = users[user].skills.length; + mostSkilledUser = user; + } +} +console.log(mostSkilledUser + " isimli kullanıcının yetenek sayısı: " + maxSkills); + +``` + +2. Count logged in users, count users having greater than equal to 50 points from the following object. + +```js + const users = { + Alex: { + email: 'alex@alex.com', + skills: ['HTML', 'CSS', 'JavaScript'], + age: 20, + isLoggedIn: false, + points: 30 + }, + Asab: { + email: 'asab@asab.com', + skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'], + age: 25, + isLoggedIn: false, + points: 50 + }, + Brook: { + email: 'daniel@daniel.com', + skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'], + age: 30, + isLoggedIn: true, + points: 50 + }, + Daniel: { + email: 'daniel@alex.com', + skills: ['HTML', 'CSS', 'JavaScript', 'Python'], + age: 20, + isLoggedIn: false, + points: 40 + }, + John: { + email: 'john@john.com', + skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'], + age: 20, + isLoggedIn: true, + points: 50 + }, + Thomas: { + email: 'thomas@thomas.com', + skills: ['HTML', 'CSS', 'JavaScript', 'React'], + age: 20, + isLoggedIn: false, + points: 40 + }, + Paul: { + email: 'paul@paul.com', + skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'], + age: 20, + isLoggedIn: false, + points: 40 + } + } + + +let pointsIsFifty = 0; + +for (let user in users) { + if (users[user].points == 50) { + pointsIsFifty++; + } +} + +console.log(pointsIsFifty); +``` + +3. Find people who are MERN stack developer from the users object +```js +//app.js +let mernStackDevelopers = []; + +for (let user in users) { + if (users[user].skills.includes('MongoDB', 'Express', 'React', 'Node')) { + mernStackDevelopers.push(user); + } +} +console.log(mernStackDevelopers) +``` +4. Set your name in the users object without modifying the original users object +```js +//app.js +const myName = "Nevzat"; +const newUsers = {...users, [myName]: {email: 'bing@microsoft.com', skills: ['search', 'AI'], age: 3, isLoggedIn: true, points: 100}}; + +console.log(newUsers); +``` +5. Get all keys or properties of users object +```js +//app.js +const keys = Object.keys(users); +console.log(keys); +``` +6. Get all the values of users object +```js +//app.js +const value = Object.keys(users); +console.log(value); +``` +7. Use the countries object to print a country name, capital, populations and languages. +```js +//app.js +for(let country in countries){ + console.log(country) + console.log(countries[country].capital) + console.log(countries[country].populations) + console.log(countries[country].langue) +} +``` + +### Exercises Level 3 + +1. Create an object literal called _personAccount_. It has _firstName, lastName, incomes, expenses_ properties and it has _totalIncome, totalExpense, accountInfo,addIncome, addExpense_ and _accountBalance_ methods. Incomes is a set of incomes and its description and expenses is a set of incomes and its description. +```js +//app.js +const personAccount = { + firstName: "Nevzat", + lastName: "Atalay", + incomes: [ + {description: "Maaş", amount: 5000}, + {description: "Kira", amount: 1000}, + {description: "Yatırım", amount: 2000} + ], + expenses: [ + {description: "Kira", amount: 500}, + {description: "Yemek", amount: 200}, + {description: "Eğlence", amount: 100} + ], + totalIncome: function() { + let sum = 0; + for (let i = 0; i < this.incomes.length; i++) { + sum += this.incomes[i].amount; + } + return sum; + }, + totalExpense: function() { + let sum = 0; + for (let i = 0; i < this.expenses.length; i++) { + sum += this.expenses[i].amount; + } + return sum; + }, + accountInfo: function() { + return "Hesap sahibi: " + this.firstName + " " + this.lastName + "\nToplam gelir: " + this.totalIncome() + "\nToplam gider: " + this.totalExpense(); + }, + addIncome: function(description, amount) { + this.incomes.push({description: description, amount: amount}); + }, + addExpense: function(description, amount) { + this.expenses.push({description: description, amount: amount}); + }, + accountBalance: function() { + return this.totalIncome() - this.totalExpense(); + } +}; + +console.log(personAccount.accountInfo()); +personAccount.addIncome("Bonus", 1000); +personAccount.addExpense("Kira", 750); +console.log(personAccount.accountBalance()); + +``` + +2. **** Questions:2, 3 and 4 are based on the following two arrays:users and products () + +```js + const users = [ + { + _id: 'ab12ex', + username: 'Alex', + email: 'alex@alex.com', + password: '123123', + createdAt:'08/01/2020 9:00 AM', + isLoggedIn: false + }, + { + _id: 'fg12cy', + username: 'Asab', + email: 'asab@asab.com', + password: '123456', + createdAt:'08/01/2020 9:30 AM', + isLoggedIn: true + }, + { + _id: 'zwf8md', + username: 'Brook', + email: 'brook@brook.com', + password: '123111', + createdAt:'08/01/2020 9:45 AM', + isLoggedIn: true + }, + { + _id: 'eefamr', + username: 'Martha', + email: 'martha@martha.com', + password: '123222', + createdAt:'08/01/2020 9:50 AM', + isLoggedIn: false + }, + { + _id: 'ghderc', + username: 'Thomas', + email: 'thomas@thomas.com', + password: '123333', + createdAt:'08/01/2020 10:00 AM', + isLoggedIn: false + } + ]; + + const products = [ + { + _id: 'eedfcf', + name: 'mobile phone', + description: 'Huawei Honor', + price: 200, + ratings: [ + { userId: 'fg12cy', rate: 5 }, + { userId: 'zwf8md', rate: 4.5 } + ], + likes: [] + }, + { + _id: 'aegfal', + name: 'Laptop', + description: 'MacPro: System Darwin', + price: 2500, + ratings: [], + likes: ['fg12cy'] + }, + { + _id: 'hedfcg', + name: 'TV', + description: 'Smart TV:Procaster', + price: 400, + ratings: [{ userId: 'fg12cy', rate: 5 }], + likes: ['fg12cy'] + } + ] + ``` + + Imagine you are getting the above users collection from a MongoDB database. + a. Create a function called signUp which allows user to add to the collection. If user exists, inform the user that he has already an account. + b. Create a function called signIn which allows user to sign in to the application + +3. The products array has three elements and each of them has six properties. + a. Create a function called rateProduct which rates the product + b. Create a function called averageRating which calculate the average rating of a product + +4. Create a function called likeProduct. This function will helps to like to the product if it is not liked and remove like if it was liked. \ No newline at end of file