Merge pull request #2 from Asabeneh/master

Obtain updated files
pull/76/head
Cornell 6 years ago committed by GitHub
commit b811ec33a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

20
.gitignore vendored

@ -14,7 +14,23 @@ day9.md
day10.md
01_02_03_days_backup.md
test.md
10_Day
11_Day
12_Day
13_Day
14_Day
15_Day
16_Day
17_Day
18_Day
19_Day
20_Day
21_Day
22_Day
23_Day
24_Day
25_Day
26_Day
27_Day
28_Day
29_Day
30_Day
test.html

@ -1,8 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<a class="header-badge" target="_blank" href="https://github.com/Asabeneh/30DaysOfJavaScript">
<img alt="GitHub stars" src="https://img.shields.io/github/stars/asabeneh/30DaysOfJavaScript?style=social">
</a>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
@ -15,6 +12,7 @@
<small> January, 2020</small>
</sub>
</div>
</div>
[<< Day 1](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/readMe.md) | [Day 3 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/03_Day/03_booleans_operators_date.md)
@ -41,7 +39,10 @@
- [String to Int](#string-to-int)
- [String to Float](#string-to-float)
- [Float to Int](#float-to-int)
- [💻 Day 2: Exercises](#-day-2-exercises)
- [💻 Day 2: Exercises](#%f0%9f%92%bb-day-2-exercises)
- [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 2
@ -134,7 +135,7 @@ role:'teaching',
country:'Finland'
}
console.log(userOne == userTwo)
console.log(userOne == userTwo) // false
```
Rule of thumb, we do not compare non-primitive data types. Do not compare array, function, or object.
@ -878,7 +879,9 @@ console.log(numInt) // 9
🌕 You are awesome. You have just completed day 2 challenges and you are two steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
# 💻 Day 2: Exercises
## 💻 Day 2: Exercises
### Exercise: Level 1
1. Declare a variable name challenge and assign it to an initial value **'30 Days Of JavaScript'**.
2. Print the string on the browser console using __console.log()__
@ -887,64 +890,70 @@ console.log(numInt) // 9
5. Change all the string to lowercase letters using __toLowerCase()__ method
6. Cut(slice) out the first word of the string using __substr()__ or __substring()__ method
7. Slice out the phrase *Days Of JavaScript* from *30 Days Of JavaScript*.
8. Use __substr__ to slice out the phase __because because because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
9. Check if the string contains a word __Script__ using __includes()__ method
10. Split the __string__ into __array__ using __split()__ method
11. Split the string 30 Days Of JavaScript at the space using __split()__ method
12. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' __split__ the string at the comma and change it to an array.
13. Change 30 Days Of JavaScript to 30 Days Of Python using __replace()__ method.
14. What is character at index 15 in '30 Days Of JavaScript' string use __charAt()__ method.
15. What is the character code of J in '30 Days Of JavaScript' string using __charCodeAt()__
16. Use __indexOf__ to determine the position of the first occurrence of a in 30 Days Of JavaScript
17. Use __lastIndexOf__ to determine the position of the last occurrence of a in 30 Days Of JavaScript.
18. Use __indexOf__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
19. Use __lastIndexOf__ to find the position of the last occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
20. Use __search__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
21. Use __trim()__ to remove if there is trailing whitespace at the beginning and the end of a string.E.g ' 30 Days Of JavaScript '.
22. Use __startsWith()__ method with the string *30 Days Of JavaScript* make the result true
23. Use __endsWith()__ method with the string *30 Days Of JavaScript* make the result true
24. Use __match()__ method to find all the as in 30 Days Of JavaScript
25. Use __match()__ to count the number all because's in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
26. Use __concat()__ and merge '30 Days of' and 'JavaScript' to a single string, '30 Days Of JavaScript'
27. Use __repeat()__ method to print 30 Days Of JavaScript 2 times
28. ** 'Love is the best thing in this world. Some found their love and some are still looking for their love.' Count the number of word love in this sentence.
29. ** Calculate the total annual income of the person by extract the numbers from the following text. 'He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month.'
30. ** Clean the following text and find the most frequent word(hint, use replace and regular express).
```js
const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%;. There $is nothing; &as& mo@re rewarding as educa@ting &and& @emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is also $the $result of &love& of tea&ching'
```
31. Using console.log() print out the following statement.
```sh
The quote 'There is no exercise better for the heart than reaching down and lifting people up.' by John Holmes teaches us to help to one another.
```
32. Using console.log() print out the following quote by Mother Teresa.
```sh
"Love is not patronizing and charity isn't about pity, it is about love. Charity and love are the same -- with charity you give love, so don't just give money but reach out your hand instead."
```
33. Check if 'on' is found in both python and jargon
34. _I hope this course is not full of jargon_. Check if _jargon_ is in the sentence.
35. Generate a random number between 0 and 100 inclusive.
36. Generate a random number between 50 and 100 inclusive.
37. Generate a random number between 0 and 255 inclusive.
38. Access the 'JavaScript' string characters using a random number.
39. Use console.log() and escape characters to print the following pattern.
```js
1 1 1 1 1
2 1 2 4 8
3 1 3 9 27
4 1 4 16 64
5 1 5 25 125
```
40. Check if typeof '10' is exactly equal to 10. If not make it exactly equal.
41. Check if parseInt('9.8') is equal to 10 if not make it exactly equal with 10.
8. Check if the string contains a word __Script__ using __includes()__ method
9. Split the __string__ into __array__ using __split()__ method
10. Split the string 30 Days Of JavaScript at the space using __split()__ method
11. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' __split__ the string at the comma and change it to an array.
12. Change 30 Days Of JavaScript to 30 Days Of Python using __replace()__ method.
13. What is character at index 15 in '30 Days Of JavaScript' string use __charAt()__ method.
14. What is the character code of J in '30 Days Of JavaScript' string using __charCodeAt()__
15. Use __indexOf__ to determine the position of the first occurrence of a in 30 Days Of JavaScript
16. Use __lastIndexOf__ to determine the position of the last occurrence of a in 30 Days Of JavaScript.
17. Use __indexOf__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
18. Use __lastIndexOf__ to find the position of the last occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
19. Use __search__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
20. Use __trim()__ to remove if there is trailing whitespace at the beginning and the end of a string.E.g ' 30 Days Of JavaScript '.
21. Use __startsWith()__ method with the string *30 Days Of JavaScript* make the result true
22. Use __endsWith()__ method with the string *30 Days Of JavaScript* make the result true
23. Use __match()__ method to find all the as in 30 Days Of JavaScript
24. Use __concat()__ and merge '30 Days of' and 'JavaScript' to a single string, '30 Days Of JavaScript'
25. Use __repeat()__ method to print 30 Days Of JavaScript 2 times
### Exercise: Level 2
1. Using console.log() print out the following statement.
```sh
The quote 'There is no exercise better for the heart than reaching down and lifting people up.' by John Holmes teaches us to help one another.
```
1. Using console.log() print out the following quote by Mother Teresa.
```sh
"Love is not patronizing and charity isn't about pity, it is about love. Charity and love are the same -- with charity you give love, so don't just give money but reach out your hand instead."
```
1. Check if typeof '10' is exactly equal to 10. If not make it exactly equal.
1. Check if parseFloat('9.8') is equal to 10 if not make it exactly equal with 10.
2. Check if 'on' is found in both python and jargon
3. _I hope this course is not full of jargon_. Check if _jargon_ is in the sentence.
4. Generate a random number between 0 and 100 inclusive.
5. Generate a random number between 50 and 100 inclusive.
6. Generate a random number between 0 and 255 inclusive.
7. Access the 'JavaScript' string characters using a random number.
8. Use console.log() and escape characters to print the following pattern.
```js
1 1 1 1 1
2 1 2 4 8
3 1 3 9 27
4 1 4 16 64
5 1 5 25 125
```
9. Use __substr__ to slice out the phase __because because because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
### Exercises: Level 3
1. 'Love is the best thing in this world. Some found their love and some are still looking for their love.' Count the number of word love in this sentence.
2. Use __match()__ to count the number all because's in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
3. Clean the following text and find the most frequent word(hint, use replace and regular express).
```js
const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %te@a@ching%;. The@re $is no@th@ing; &as& mo@re rewarding as educa@ting &and& @emp%o@weri@ng peo@ple. ;I found tea@ching m%o@re interesting tha@n any ot#her %jo@bs. %Do@es thi%s mo@tiv#ate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is al@so $the $resu@lt of &love& of tea&ching'
```
4. Calculate the total annual income of the person by extract the numbers from the following text. 'He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month.'
🎉 CONGRATULATIONS ! 🎉

@ -1,8 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<a class="header-badge" target="_blank" href="https://github.com/Asabeneh/30DaysOfJavaScript">
<img alt="GitHub stars" src="https://img.shields.io/github/stars/asabeneh/30DaysOfJavaScript?style=social">
</a>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
@ -49,14 +46,10 @@
- [Getting minutes](#getting-minutes)
- [Getting seconds](#getting-seconds)
- [Getting time](#getting-time)
- [💻 Day 3: Exercises](#-day-3-exercises)
- [1. Exercises: Data types Part](#1-exercises-data-types-part)
- [2. Exercises: Arithmetic Operators Part](#2-exercises-arithmetic-operators-part)
- [3. Exercises: Booleans Part](#3-exercises-booleans-part)
- [4. Exercises: Comparison Operators](#4-exercises-comparison-operators)
- [5. Exercises: Logical Operators](#5-exercises-logical-operators)
- [6 Ternary Operator](#6-ternary-operator)
- [7. Exercises: Date time Object](#7-exercises-date-time-object)
- [💻 Day 3: Exercises](#%f0%9f%92%bb-day-3-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 3
@ -149,6 +142,9 @@ let powerOf = numOne ** numTwo
console.log(sum, diff, mult, div, remainder, powerOf) // 7,1,12,1.33,1, 64
```
```js
let PI = 3.14
let radius = 100 // length in meter
@ -479,6 +475,7 @@ console.log(now.getTime()) // 1578092201341, this is the number of seconds passe
```js
const allSeconds = Date.now() //
console.log(allSeconds) // 1578092201341, this is the number of seconds passed from January 1, 1970 to January 4, 2020 00:56:41
const timeInSeconds = new Date().getTime()
console.log(allSeconds == timeInSeconds) // true
```
@ -493,21 +490,60 @@ const month = now.getMonth() + 1 // return month(0 - 11)
const date = now.getDate() // return date (1 - 31)
const hours = now.getHours() // return number (0 - 23)
const minutes = now.getMinutes() // return number (0 -59)
console.log(`${date}/${month}/${year} ${hours}:${minutes}`) // 4/1/2020 0:56
```
🌕 You have boundless energy. You have just completed day 3 challenges and you are three steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
# 💻 Day 3: Exercises
## 1. Exercises: Data types Part
## 💻 Day 3: Exercises
### Exercises: Level 1
1. Declare firstName, lastName, country, city, age, isMarried, year variable and assign value to it and use the typeof operator to check different data types.
2. Check if type of '10' is equal to 10
3. Check if parseInt('9.8') is equal to 10
4. Boolean value is either true or false.
1. Write three JavaScript statement which provide truthy value.
2. Write three JavaScript statement which provide falsy value.
5. Figure out the result of the following comparison expression first without using console.log(). After you decide the result confirm it using console.log()
1. 4 > 3
2. 4 >= 3
3. 4 < 3
4. 4 <= 3
5. 4 == 4
6. 4 === 4
7. 4 != 4
8. 4 !== 4
9. 4 != '4'
10. 4 == '4'
11. 4 === '4'
12. Find the length of python and jargon and make a falsy comparison statement.
6. Figure out the result of the following expressions first without using console.log(). After you decide the result confirm it by using console.log()
1. 4 > 3 && 10 < 12
2. 4 > 3 && 10 > 12
3. 4 > 3 || 10 < 12
4. 4 > 3 || 10 > 12
5. !(4 > 3)
6. !(4 < 3)
7. !(false)
8. !(4 > 3 && 10 < 12)
9. !(4 > 3 && 10 > 12)
10. !(4 === '4')
11. There is no 'on' in both dragon and python
1. Declare firstName, lastName, country, city, age, isMarried, year variable and assign value to it
1. The JavaScript typeof operator uses to check different data types. Check the data type of each variables from question number 1.
1. Check if type of '10' is equal to 10
1. Check if parseInt('9.8') is equal to 10
7. Use the Date object to do the following activities
1. What is the year today?
2. What is the month today as a number?
3. What is the date today?
4. What is the day today as a number?
5. What is the hours now?
6. What is the minutes now?
7. Find out the numbers of seconds elapsed from January 1, 1970 to now.
## 2. Exercises: Arithmetic Operators Part
### Exercises: Level 2
1. Write a script that prompt the user to enter base and height of the triangle and calculate an area of a triangle (area = 0.5 x b x h).
@ -534,75 +570,25 @@ console.log(`${date}/${month}/${year} ${hours}:${minutes}`) // 4/1/2020 0:56
1. Calculate the value of y (y = x^2 + 6x + 9). Try to use different x values and figure out at what x value y is 0.
1. Writ a script that prompt a user to enters hours and rate per hour. Calculate pay of the person?
```sh
Enter hours: 40
Enter rate per hour: 28
Your weekly earning is 1120
```
1. Write a script that prompt the user to enter number of years. Calculate the number of seconds a person can live. Assume some one lives just hundred years
```sh
Enter number of yours you live: 100
You lived 3153600000 seconds.
```
## 3. Exercises: Booleans Part
Boolean value is either true or false.
1. Write three JavaScript statement which provide truthy value.
1. Write three JavaScript statement which provide falsy value.
## 4. Exercises: Comparison Operators
Figure out the result of the following comparison expression first without using console.log(). After you decide the result confirm it using console.log()
1. 4 > 3
1. 4 >= 3
1. 4 < 3
1. 4 <= 3
1. 4 == 4
1. 4 === 4
1. 4 != 4
1. 4 !== 4
1. 4 != '4'
1. 4 == '4'
1. 4 === '4'
Find the length of python and jargon and make a falsy comparison statement.
## 5. Exercises: Logical Operators
1. Figure out the result of the following expressions first without using console.log(). After you decide the result confirm it by using console.log()
1. 4 > 3 && 10 < 12
2. 4 > 3 && 10 > 12
3. 4 > 3 || 10 < 12
4. 4 > 3 || 10 > 12
5. !(4 > 3)
6. !(4 < 3)
7. !(false)
8. !(4 > 3 && 10 < 12)
9. !(4 > 3 && 10 > 12)
10. !(4 === '4')
2. There is no 'on' in both dragon and python
## 6 Ternary Operator
```sh
Enter hours: 40
Enter rate per hour: 28
Your weekly earning is 1120
```
1. If the length of your name is greater than 7 say, your name is long else say your name is short.
1. Compare your first name length and your family name length and you should get this output.
```js
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
```
```js
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
```
```sh
//Output
Your first name, Asabeneh is longer than your family name, Yetayeh
```
```sh
Your first name, Asabeneh is longer than your family name, Yetayeh
```
1. Declare two variables _myAge_ and _yourAge_ and assign them initial values and myAge and yourAge.
Output:
```js
let myAge = 250
@ -610,32 +596,36 @@ Your first name, Asabeneh is longer than your family name, Yetayeh
```
```sh
//output
I am 225 years older than you.
```
1. Using prompt get the year the user was born and if the user is 18 or above allow the user to drive if not tell the user to wait a certain amount of years.
```sh
// if the age is 25
You are 25. You are old enough to drive
// if the age is under 18
You are 15. You will be allowed to drive after 3 years.
```
## 7. Exercises: Date time Object
1. What is the year today?
1. What is the month today as a number?
1. What is the date today?
1. What is the day today as a number?
1. What is the hours now?
1. What is the minutes now?
1. Find out the numbers of seconds elapsed from January 1, 1970 to now.
1. Create a human readable time format
1. YYY-MM-DD HH:mm:ss
2. DD-MM-YYYY HH:mm:ss
3. DD/MM/YYY HH:mm:ss
```sh
Enter birth year: 1995
You are 25. You are old enough to drive
Enter birth year: 2005
You are 15. You will be allowed to drive after 3 years.
```
1. Write a script that prompt the user to enter number of years. Calculate the number of seconds a person can live. Assume some one lives just hundred years
```sh
Enter number of yours you live: 100
You lived 3153600000 seconds.
```
1. Create a human readable time format using the Date time object
1. YYY-MM-DD HH:mm
2. DD-MM-YYYY HH:mm
3. DD/MM/YYY HH:mm
### Exercises: Level 3
1. Create a human readable time format using the Date time object. The hour and the minute should be all time two digits(7 hours should be 07 and 5 minutes should be 05 )
1. YYY-MM-DD HH:mm eg. 20120-01-02 07:05
🎉 CONGRATULATIONS ! 🎉

@ -1,8 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<a class="header-badge" target="_blank" href="https://github.com/Asabeneh/30DaysOfJavaScript">
<img alt="GitHub stars" src="https://img.shields.io/github/stars/asabeneh/30DaysOfJavaScript?style=social">
</a>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
@ -27,7 +24,10 @@
- [if else if else](#if-else-if-else)
- [Switch](#switch)
- [Ternary Operators](#ternary-operators)
- [💻 Exercise : Conditionals](#-exercise--conditionals)
- [💻 Exercises](#%f0%9f%92%bb-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 4
@ -254,7 +254,9 @@ isRaining
🌕 You are extraordinary and you have a remarkable potential. You have just completed day 4 challenges and you are four steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
# 💻 Exercise : Conditionals
## 💻 Exercises
### Exercises: Level 1
1. Get user input using prompt(“Enter your age:”). If user is 18 or older , give feedback:You are old enough to drive but if not 18 give feedback to wait for the years he supposed to wait for.
@ -287,19 +289,6 @@ isRaining
4 is greater than 3
```
1. Write a code which give grade students according to theirs scores:
- 80-100, A
- 70-89, B
- 60-69, C
- 50-59, D
- 0 -49, F
1. Check if the season is Autumn, Winter, Spring or Summer.
If the user input is:
- September, October or November, the season is Autumn.
- December, January or February, the season is Winter.
- March, April or May, the season is Spring
- June, July or August, the season is Summer
1. Even numbers are divisible by 2 and the remainder is zero. How do you check if a number is even or not using JavaScript?
```sh
@ -310,6 +299,20 @@ isRaining
9 is is an odd number.
```
### Exercises: Level 2
1. Write a code which can give grade to students according to theirs scores:
- 80-100, A
- 70-89, B
- 60-69, C
- 50-59, D
- 0-49, F
1. Check if the season is Autumn, Winter, Spring or Summer.
If the user input is:
- September, October or November, the season is Autumn.
- December, January or February, the season is Winter.
- March, April or May, the season is Spring
- June, July or August, the season is Summer
1. Check if a day is weekend day or a working day. Your script will take day as an input.
```sh
@ -326,6 +329,8 @@ isRaining
Friday is a work day.
```
### Exercises: Level 3
1. Write a program which tells the number days in a month.
```sh
@ -342,7 +347,6 @@ isRaining
February has 28 days.
```
🎉 CONGRATULATIONS ! 🎉
[<< Day 3](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/03_Day/03_booleans_operators_date.md) | [Day 5 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/05_Day/05_day_arrays.md)

@ -1,8 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<a class="header-badge" target="_blank" href="https://github.com/Asabeneh/30DaysOfJavaScript">
<img alt="GitHub stars" src="https://img.shields.io/github/stars/asabeneh/30DaysOfJavaScript?style=social">
</a>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
@ -47,6 +44,9 @@
- [Sorting elements in array](#sorting-elements-in-array)
- [Array of arrays](#array-of-arrays)
- [💻 Exercise](#%f0%9f%92%bb-exercise)
- [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2)
- [Exercise: Level 3](#exercise-level-3)
# 📔 Day 5
@ -662,6 +662,8 @@ console.log(arrayOfArray[0]) // [1, 2, 3]
## 💻 Exercise
### Exercise: Level 1
```js
const countries = [
'Albania',
@ -711,6 +713,9 @@ const webTechs = [
1. Remove the middle IT company or companies from the array
1. Remove the last IT company from the array
1. Remove all IT companies
### 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 ans store the webTechs array in to this file. Access both file in main.js file
1. First remove all the functions and change the string to array and count the number of words in the array
@ -723,6 +728,7 @@ const webTechs = [
```sh
["I", "love", "teaching", "and", "empowering", "people", "I", "teach", "HTML", "CSS", "JS", "React", "Python"]
13
```
@ -751,6 +757,8 @@ const webTechs = [
["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"]
```
### Exercise: Level 3
1. The following is an array of 10 students ages:
```js
@ -758,15 +766,13 @@ const webTechs = [
```
- Sort the array and find the min and max age
- Find the min age and the 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](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)
1. Find the middle country(ies) in the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)
1. Find the middle country(ies) in the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)
1. 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.
2. 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.
🎉 CONGRATULATIONS ! 🎉

@ -1,8 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<a class="header-badge" target="_blank" href="https://github.com/Asabeneh/30DaysOfJavaScript">
<img alt="GitHub stars" src="https://img.shields.io/github/stars/asabeneh/30DaysOfJavaScript?style=social">
</a>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
@ -28,7 +25,10 @@
- [for of loop](#for-of-loop)
- [break](#break)
- [continue](#continue)
- [💻 Exercises:Day 6](#-exercisesday-6)
- [💻 Exercises:Day 6](#%f0%9f%92%bb-exercisesday-6)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 6
@ -217,6 +217,8 @@ content will added soon
## 💻 Exercises:Day 6
### Exercises: Level 1
```js
const countries = [
'Albania',
@ -322,7 +324,9 @@ content will added soon
5j2khz
```
16. Develop a small script which generate any number of characters random id:
### Exercises: Level 2
1. Develop a small script which generate any number of characters random id:
```sh
fe3jo1gl124g
@ -332,31 +336,31 @@ content will added soon
xkqci4utda1lmbelpkm03rba
```
17. Write a script which generates a random hexadecimal number.
1. Write a script which generates a random hexadecimal number.
```sh
'#ee33df'
```
18. Write a script which generates a random rgb color number.
1. Write a script which generates a random rgb color number.
```sh
rgb(240,180,80)
```
19. Using the above countries array, create the following new array.
1. Using the above countries array, create the following new array.
```sh
["ALBANIA", "BOLIVIA", "CANADA", "DENMARK", "ETHIOPIA", "FINLAND", "GERMANY", "HUNGARY", "IRELAND", "JAPAN", "KENYA"]
```
20. Using the above countries array, create an array for countries length'.
1. Using the above countries array, create an array for countries length'.
```sh
[7, 7, 6, 7, 8, 7, 7, 7, 7, 5, 5]
```
21. Use the countries array to create the following array of arrays:
1. Use the countries array to create the following array of arrays:
```sh
[
@ -374,42 +378,41 @@ content will added soon
]
```
22. In above countries array, check if there is a country or countries containing the word 'land'. If there are countries containing 'land', print it as array. If there is no country containing the word 'land', print 'These are countries without land'.
1. In above countries array, check if there is a country or countries containing the word 'land'. If there are countries containing 'land', print it as array. If there is no country containing the word 'land', print 'All these are countries without land'.
```sh
['Finland', 'Iceland']
```
23. In above countries array, check if there a country or countries end with a substring 'ia'. If there are countries end with, print it as array. If there is no country containing the word 'land', print 'These are countries ends without ia'.
1. In above countries array, check if there is a country or countries end with a substring 'ia'. If there are countries end with, print it as array. If there is no country containing the word 'ai', print 'These are countries ends without ia'.
```sh
['Albania', 'Bolivia','Ethiopia']
```
24. Using the above countries array, find the country containing the biggest number of characters.
1. Using the above countries array, find the country containing the biggest number of characters.
```sh
Ethiopia
```
25. Using the above countries array, find the country containing only 5 characters.
1. Using the above countries array, find the country containing only 5 characters.
```sh
['Japan', 'Kenya']
```
26. Find the longest word in the webTechs array
27. Use the webTechs are to create the following array of arrays:
1. Find the longest word in the webTechs array
1. Use the webTechs are to create the following array of arrays:
```sh
[["HTML", 4], ["CSS", 3],["JavaScript", 10],["React", 5],["Redux", 5],["Node", 4],["MongoDB", 7]]
```
28. An application created using MongoDB, Express, React and Node is called a MERN stack. Create the acronym MERN by using the array mernStack
29. Iterate through the array, ["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"] using a for loop or for of loop and print out the items.
30. This is a fruit array , ['banana', 'orange', 'mango', 'lemon'] reverse the order using loop without using a reverse method.
31. Print all the elements of array as shown below.
1. An application created using MongoDB, Express, React and Node is called a MERN stack. Create the acronym MERN by using the array mernStack
1. Iterate through the array, ["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"] using a for loop or for of loop and print out the items.
1. This is a fruit array , ['banana', 'orange', 'mango', 'lemon'] reverse the order using loop without using a reverse method.
1. Print all the elements of array as shown below.
```js
const fullStack = [
@ -427,15 +430,18 @@ content will added soon
EXPRESS
MONGODB
```
32. Copy countries array(Avoid mutation)
33. Arrays are mutable. Create a copy of array which does not modify the original. Sort the copied array and store in a variable sortedCountries
34. Sort the webTechs array and mernStack array
35. Extract all the countries contain the word 'land' from the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) and print it as array
36. Find the country containing the hightest number of characters in the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)
37. Extract all the countries contain the word 'land' from the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) and print it as array
38. Extract all the countries containing only four characters from the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) and print it as array
39. Extract all the countries containing two or more words from the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) and print it as array
40. Reverse the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) and capitalize each country and stored it as an array
### Exercises: Level 3
1. Copy countries array(Avoid mutation)
1. Arrays are mutable. Create a copy of array which does not modify the original. Sort the copied array and store in a variable sortedCountries
1. Sort the webTechs array and mernStack array
1. Extract all the countries contain the word 'land' from the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) and print it as array
1. Find the country containing the hightest number of characters in the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)
1. Extract all the countries contain the word 'land' from the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) and print it as array
1. Extract all the countries containing only four characters from the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) and print it as array
1. Extract all the countries containing two or more words from the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) and print it as array
1. Reverse the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) and capitalize each country and stored it as an array
🎉 CONGRATULATIONS ! 🎉

@ -1,8 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<a class="header-badge" target="_blank" href="https://github.com/Asabeneh/30DaysOfJavaScript">
<img alt="GitHub stars" src="https://img.shields.io/github/stars/asabeneh/30DaysOfJavaScript?style=social">
</a>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
@ -37,7 +34,10 @@
- [Arrow Function](#arrow-function)
- [Function with default parameters](#function-with-default-parameters)
- [Function declaration versus Arrow function](#function-declaration-versus-arrow-function)
- [💻 Exercises](#-exercises)
- [💻 Exercises](#%f0%9f%92%bb-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 7
@ -507,6 +507,8 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
## 💻 Exercises
### Exercises: Level 1
1. Declare a function _fullName_ and it print out your full name.
2. Declare a function _fullName_ and now it takes firstName, lastName as a parameter and it returns your full - name.
3. Declare a function _addNumbers_ and it takes two two parameters and it returns sum.
@ -537,8 +539,10 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
0
```
16. Linear equation is calculated as follows: _ax + by + c = 0_. Write a function which calculates value of a linear equation, _solveLinEquation_.
17. Quadratic equation is calculated as follows: _ax2 + bx + c = 0_. Write a function which calculates value or values of a quadratic equation, _solveQuadEquation_.
### Exercises: Level 2
1. Linear equation is calculated as follows: _ax + by + c = 0_. Write a function which calculates value of a linear equation, _solveLinEquation_.
1. Quadratic equation is calculated as follows: _ax2 + bx + c = 0_. Write a function which calculates value or values of a quadratic equation, _solveQuadEquation_.
```js
console.log(solveQuadratic()) // {0}
@ -549,22 +553,22 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
console.log(solveQuadratic(1, -1, 0)) //{1, 0}
```
18. Declare a function name _printArray_. It takes array as a parameter and it prints out each value of the array.
19. 11. Write a function name _showDateTime_ which shows time in this format: 08/01/2020 04:08 using the Date object.
1. Declare a function name _printArray_. It takes array as a parameter and it prints out each value of the array.
1. Write a function name _showDateTime_ which shows time in this format: 08/01/2020 04:08 using the Date object.
```sh
showDateTime()
08/01/2020 04:08
```
20. Declare a function name _swapValues_. This function swaps value of x to y.
1. Declare a function name _swapValues_. This function swaps value of x to y.
```js
swapValues(3, 4) // x => 4, y=>3
swapValues(4, 5) // x = 5, y = 4
```
21. Declare a function name _reverseArray_. It takes array as a parameter and it returns the reverse of the array (don't use method).
1. Declare a function name _reverseArray_. It takes array as a parameter and it returns the reverse of the array (don't use method).
```js
console.log(reverseArray([1, 2, 3, 4, 5]))
@ -573,13 +577,13 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
//['C', 'B', 'A']
```
22. Declare a function name _capitalizeArray_. It takes array as a parameter and it returns the - capitalizedarray.
23. Declare a function name _addItem_. It takes an item parameter and it returns an array after adding the item
24. Declare a function name _removeItem_. It takes an index parameter and it returns an array after removing an item
25. Declare a function name _sumOfNumbers_. It takes a number parameter and it adds all the numbers in that range.
26. Declare a function name _sumOfOdds_. It takes a number parameter and it adds all the odd numbers in that - range.
27. Declare a function name _sumOfEven_. It takes a number parameter and it adds all the even numbers in that - range.
28. Declare a function name evensAndOdds . It takes a positive integer as parameter and it counts number of evens and odds in the number.
1. Declare a function name _capitalizeArray_. It takes array as a parameter and it returns the - capitalizedarray.
1. Declare a function name _addItem_. It takes an item parameter and it returns an array after adding the item
1. Declare a function name _removeItem_. It takes an index parameter and it returns an array after removing an item
1. Declare a function name _sumOfNumbers_. It takes a number parameter and it adds all the numbers in that range.
1. Declare a function name _sumOfOdds_. It takes a number parameter and it adds all the odd numbers in that - range.
1. Declare a function name _sumOfEven_. It takes a number parameter and it adds all the even numbers in that - range.
1. Declare a function name evensAndOdds . It takes a positive integer as parameter and it counts number of evens and odds in the number.
```sh
evensAndOdds(100);
@ -587,30 +591,32 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
The number of evens are 51.
```
29. Write a function which takes any number of arguments and return the sum of the arguments
1. Write a function which takes any number of arguments and return the sum of the arguments
```js
sum(1, 2, 3) // -> 6
sum(1, 2, 3, 4) // -> 10
```
30. Writ a function which generates a _randomUserIp_.
31. Write a function which generates a _randomMacAddress_
32. Declare a function name _randomHexaNumberGenerator_. When this function is called it generates a random hexadecimal number. The function return the hexadecimal number.
1. Writ a function which generates a _randomUserIp_.
1. Write a function which generates a _randomMacAddress_
1. Declare a function name _randomHexaNumberGenerator_. When this function is called it generates a random hexadecimal number. The function return the hexadecimal number.
```sh
console.log(randomHexaNumberGenerator());
'#ee33df'
```
33. Declare a function name _userIdGenerator_. When this function is called it generates seven character id. The function return the id.
1. Declare a function name _userIdGenerator_. When this function is called it generates seven character id. The function return the id.
```sh
console.log(userIdGenerator());
41XTDbE
```
34. Modify question number n . Declare a function name _userIdGeneratedByUser_. It doesnt 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.
### Exercises: Level 3
1. Modify question number n . Declare a function name _userIdGeneratedByUser_. It doesnt 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.
```sh
userIdGeneratedByUser()
@ -629,18 +635,18 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
'
```
35. Write a function name _rgbColorGenerator_ and it generates rgb colors.
1. Write a function name _rgbColorGenerator_ and it generates rgb colors.
```sh
rgbColorGenerator()
rgb(125,244,255)
```
36. Write a function **_arrayOfHexaColors_** which return any number of hexadecimal colors in an array.
37. Write a function **_arrayOfRgbColors_** which return any number of RGB colors in an array.
38. Write a function **_convertHexaToRgb_** which converts hexa color to rgb and it returns an rgb color.
39. Write a function **_convertRgbToHexa_** which converts rgb to hexa color and it returns an hexa color.
40. Write a function **_generateColors_** which can generate any number of hexa or rgb colors.
1. Write a function **_arrayOfHexaColors_** which return any number of hexadecimal colors in an array.
1. Write a function **_arrayOfRgbColors_** which return any number of RGB colors in an array.
1. Write a function **_convertHexaToRgb_** which converts hexa color to rgb and it returns an rgb color.
1. Write a function **_convertRgbToHexa_** which converts rgb to hexa color and it returns an hexa color.
1. Write a function **_generateColors_** which can generate any number of hexa or rgb colors.
```js
console.log(generateColors('hexa', 3)) // ['#a3e12f', '#03ed55', '#eb3d2b']
@ -649,34 +655,50 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
console.log(generateColors('rgb', 1)) // 'rgb(33,79, 176)'
```
41. Call your function _shuffleArray_, it takes an array as a parameter and it returns a shuffled array
42. Call your function _factorial_, it takes a whole number as a parameter and it return a factorial of the number
43. Call your function _isEmpty_, it takes a parameter and it checks if it is empty or not
44. Call your function _sum_, it takes any number of arguments and it returns the sum.
45. 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.
46. 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.
47. 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'.
1. Call your function _shuffleArray_, it takes an array as a parameter and it returns a shuffled array
1. Call your function _factorial_, it takes a whole number as a parameter and it return a factorial of the number
1. Call your function _isEmpty_, it takes a parameter and it checks if it is empty or not
1. Call your function _sum_, it takes any number of arguments and it returns the sum.
1. 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.
1. 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.
1. 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
console.log(modifyArray(['Avocado', 'Tomato', 'Potato','Mango', 'Lemon','Carrot']);
// →['Avocado', 'Tomato', 'Potato','Mango', 'LEMON', 'Carrot']
```
```sh
['Avocado', 'Tomato', 'Potato','Mango', 'LEMON', 'Carrot']
```
```js
console.log(modifyArray(['Google', 'Facebook','Apple', 'Amazon','Microsoft', 'IBM']);
// →['Google', 'Facebook','Apple', 'Amazon','MICROSOFT', 'IBM']
```
```sh
['Google', 'Facebook','Apple', 'Amazon','MICROSOFT', 'IBM']
```
```js
console.log(modifyArray(['Google', 'Facebook','Apple', 'Amazon']);
// →'Not Found'
```
48. Write a function called _isPrime_, which checks if a number is prime number.
49. Write a functions which checks if all items are unique in the array.
50. Write a function which checks if all the items of the array are the same data type.
51. 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.
52. Write a function which returns array of seven random numbers in a range of 0-9. All the numbers must be unique.
```sh
'Not Found'
```
1. Write a function called _isPrime_, which checks if a number is prime number.
1. Write a functions which checks if all items are unique in the array.
1. Write a function which checks if all the items of the array are the same data type.
1. 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.
1. Write a function which returns array of seven random numbers in a range of 0-9. All the numbers must be unique.
```js
sevenRandomNumbers()[(1, 4, 5, 7, 9, 8, 0)]
sevenRandomNumbers()
[(1, 4, 5, 7, 9, 8, 0)]
```
53. Write a function called reverseCountries, it takes countries array and first it copy the array and returns the reverse of the original array
1. Write a function called reverseCountries, it takes countries array and first it copy the array and returns the reverse of the original array
🎉 CONGRATULATIONS ! 🎉

@ -1,8 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<a class="header-badge" target="_blank" href="https://github.com/Asabeneh/30DaysOfJavaScript">
<img alt="GitHub stars" src="https://img.shields.io/github/stars/asabeneh/30DaysOfJavaScript?style=social">
</a>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
@ -10,11 +7,10 @@
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> January, 2020</small>
</sub>
<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> January, 2020</small>
</sub>
</div>
[<< Day 7](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/07_Day/07_day_functions.md) | [Day 9 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/09_Day/09_day_higher_order_functions.md)
@ -38,6 +34,8 @@
- [Getting object keys and values using Object.entries()](#getting-object-keys-and-values-using-objectentries)
- [Checking properties using hasOwnProperty()](#checking-properties-using-hasownproperty)
- [💻 Exercises](#%f0%9f%92%bb-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
# 📔 Day 8
@ -422,12 +420,17 @@ console.log(copyPerson.hasOwnProperty('score'))
## 💻 Exercises
### Exercises: Level 1
1. Create an empty object called dog
1. Print the the dog object on the console
1. Add name, legs, color, age and bark properties for the dog object. The bark property is a method which return _woof woof_
1. Get name, legs, color, age and bark value from the dog object
1. Set new properties the dog object: breed, getDogInfo
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.
### Exercises: Level 2
1. Find the person who has many skills in the users object.
1. Count logged in users,count users having greater than equal to 50 points from the following object.
````js
@ -483,14 +486,101 @@ console.log(copyPerson.hasOwnProperty('score'))
}
}```
````
1. Find people who are MERN stack developer from the users object
1. Set your name in the users object without modifying the original users object
1. Get all keys or properties of users object
1. Get all the values of users object
1. Use the countries object to print a country name, capital, populations and languages.
### 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.
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.
🎉 CONGRATULATIONS ! 🎉

@ -1,8 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<a class="header-badge" target="_blank" href="https://github.com/Asabeneh/30DaysOfJavaScript">
<img alt="GitHub stars" src="https://img.shields.io/github/stars/asabeneh/30DaysOfJavaScript?style=social">
</a>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
@ -10,14 +7,13 @@
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> January, 2020</small>
</sub>
<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> January, 2020</small>
</sub>
</div>
[<< Day 8](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/08_Day/08_day_objects.md) | [Day 10 >>](#)
[<< Day 8](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/08_Day/08_day_objects.md) | [Day 10 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/10_Day/10_day_Set_and_Map.md)
![Day 5](../images/banners/day_1_9.png)
@ -25,7 +21,7 @@
- [Higher Order Function](#higher-order-function)
- [Callback](#callback)
- [Returning function](#returning-function)
- [setTime](#settime)
- [setting time](#setting-time)
- [setInterval](#setinterval)
- [setTimeout](#settimeout)
- [Functional Programming](#functional-programming)
@ -35,13 +31,17 @@
- [reduce](#reduce)
- [every](#every)
- [find](#find)
- [some](#some)
- [findIndex](#findindex)
- [some](#some)
- [sort](#sort)
- [Sorting string values](#sorting-string-values)
- [Sorting Numeric values](#sorting-numeric-values)
- [Sorting Object Arrays](#sorting-object-arrays)
- [💻 Exercises](#%f0%9f%92%bb-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Day 9
## Higher Order Function
@ -54,7 +54,7 @@ A callback is a function which can be passed as parameter to other function. See
```js
// a callback function, the function could be any name
const callBack = (n) => {
const callback = (n) => {
return n ** 2
}
@ -63,13 +63,14 @@ function cube(callback, n) {
return callback(n) * n
}
console.log(cube(square, 3))
console.log(cube(callback, 3))
```
### Returning function
Higher order functions return function as a value
```js
// Higher order function returning an other function
const higherOrder = n => {
@ -85,7 +86,7 @@ const higherOrder = n => {
console.log(higherOrder(2)(3)(10))
```
Let us see were we use call back functions.For instance the *forEach* method uses call back.
Let us see were we use call back functions.For instance the _forEach_ method uses call back.
```js
const numbers = [1, 2, 3, 4]
@ -102,6 +103,10 @@ const sumArray = arr => {
console.log(sumArray(numbers))
```
```sh
15
```
The above example can be simplified as follows:
```js
@ -118,7 +123,16 @@ const sumArray = arr => {
console.log(sumArray(numbers))
```
### setTime
```sh
15
```
### setting time
In JavaScript we can execute some activity on certain interval of time or we can schedule(wait) for sometime to execute some activities.
- setInterval
- setTimeout
#### setInterval
@ -126,15 +140,14 @@ In JavaScript, we use setInterval higher order function to do some activity cont
```js
// syntax
function callBack () {
function callBack() {
// code goes here
}
setInterval(callback, duration)
```
```js
function sayHello () {
function sayHello() {
console.log('Hello')
}
setInterval(sayHello, 2000) // it prints hello in every 2 seconds
@ -146,15 +159,14 @@ In JavaScript, we use setTimeout higher order function to execute some action at
```js
// syntax
function callBack () {
function callback() {
// code goes here
}
setTimeout(callback, duration) // duration in milliseconds
```
```js
function sayHello () {
function sayHello() {
console.log('Hello')
}
setTimeout(sayHello, 2000) // it prints hello after it waits for 2 seconds.
@ -162,14 +174,14 @@ setTimeout(sayHello, 2000) // it prints hello after it waits for 2 seconds.
## Functional Programming
Instead of writing regular loop, latest version of JavaScript introduced lots of built in methods which can help us to solve complicated problems. All builtin methods take callback function. In this section, we will see *forEach*, *map*, *filter*, *reduce*, *find*, *every*, *some*, and *sort*.
Instead of writing regular loop, latest version of JavaScript introduced lots of built in methods which can help us to solve complicated problems. All builtin methods take callback function. In this section, we will see _forEach_, _map_, _filter_, _reduce_, _find_, _every_, _some_, and _sort_.
### forEach
*forEach*: Iterate an array elements. We use *forEach* only with arrays. It takes a callback function with elements, index parameter and array itself. The index and the array optional.
_forEach_: Iterate an array elements. We use _forEach_ only with arrays. It takes a callback function with elements, index parameter and array itself. The index and the array optional.
```js
arr.forEach(function(element, index, arr){
arr.forEach(function(element, index, arr) {
console.log(index, element, arr)
})
// The above code can be written using arrow function
@ -180,11 +192,32 @@ arr.forEach((element, index, arr) => {
arr.forEach((element, index, arr) => console.log(index, element, arr))
```
```js
let sum = 0;
const numbers = [1,2,3,4,5];
numbers.forEach(num => console.log(num)))
console.log(sum)
```
```sh
1
2
3
4
5
```
```js
let sum = 0;
const numbers = [1,2,3,4,5];
numbers.forEach(num => sum += num))
// 15
console.log(sum)
```
```sh
15
```
```js
@ -202,10 +235,10 @@ ICELAND
### map
*map*: Iterate an array elements and modify the array elements. It takes a callback function with elements and index parameter and return the modified array.
_map_: Iterate an array elements and modify the array elements. It takes a callback function with elements and index parameter and return a new array.
```js
const modifiedArray = arr.map(function(element, index){
const modifiedArray = arr.map(function(element, index) {
return element
})
```
@ -215,15 +248,24 @@ const modifiedArray = arr.map(function(element, index){
const modifiedArray = arr.map((element,index) => element);
*/
//Example
const numbers = [1,2,3,4,5]
const numbersSquare = numbers.map((num) => num * num)
console.log(numbersSquare) // [1,4,9,16,25]
const numbers = [1, 2, 3, 4, 5]
const numbersSquare = numbers.map(num => num * num)
console.log(numbersSquare)
```
```sh
[1, 4, 9, 16, 25]
```
```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const namesToUpperCase = names.map((name) => name.toUpperCase())
console.log(namesToUpperCase) //['ASABENEH', 'MATHIAS', 'ELIAS', 'BROOK']
const namesToUpperCase = names.map(name => name.toUpperCase())
console.log(namesToUpperCase)
```
```sh
['ASABENEH', 'MATHIAS', 'ELIAS', 'BROOK']
```
```js
@ -240,13 +282,9 @@ const countries = [
'Japan',
'Kenya'
]
const countriesToUpperCase = countries.map(function(country){
let countryCode = country.toUpperCase().slice(0, 3)
let country = country.length
return []
})
const countriesToUpperCase = countries.map(country => country.toUpperCase())
console.log(countriesToUpperCase)
// ['ALBANIA', 'BOLIVIA', 'CANADA', 'DENMARK', 'ETHIOPIA', 'FINLAND', 'GERMANY', 'HUNGARY', 'IRELAND', 'JAPAN', 'KENYA']
/*
// Arrow function
const countriesToUpperCase = countries.map((country) => {
@ -255,24 +293,59 @@ const countriesToUpperCase = countries.map((country) => {
//Explicit return arrow function
const countriesToUpperCase = countries.map(country => country.toUpperCase());
*/
```
```sh
['ALBANIA', 'BOLIVIA', 'CANADA', 'DENMARK', 'ETHIOPIA', 'FINLAND', 'GERMANY', 'HUNGARY', 'IRELAND', 'JAPAN', 'KENYA']
```
```js
const countriesFirstThreeLetters = countries.map(country =>
country.toUpperCase().slice(0, 3)
)
```
```sh
 ["ALB", "BOL", "CAN", "DEN", "ETH", "FIN", "GER", "HUN", "IRE", "JAP", "KEN"]
```
### filter
*Filter*: Filter out items which full fill filtering conditions
_Filter_: Filter out items which full fill filtering conditions and return a new array.
```js
//Filter countries containing land
const countriesContainingLand = countries.filter(country => country.includes('land'));
console.log(countriesContainingLand ) //['Finland', 'Ireland']
const countriesContainingLand = countries.filter(country =>
country.includes('land')
)
console.log(countriesContainingLand)
```
```sh
['Finland', 'Ireland']
```
```js
const countriesEndsByia = countries.filter(country => country.includes('ia'))
console.log(countriesEndsByia)
```
const countriesEndsByia = countries.filter(country => country.includes('ia'));
console.log(countriesEndsByia) //['Albania', 'Bolivia','Ethiopia']
```sh
['Albania', 'Bolivia','Ethiopia']
```
const countriesHaveFiveLetters = countries.filter(country => country.length === 5);
console.log(countriesHaveFiveLetters ) //  ['Japan', 'Kenya']
```js
const countriesHaveFiveLetters = countries.filter(
country => country.length === 5
)
console.log(countriesHaveFiveLetters)
```
```sh
['Japan', 'Kenya']
```
```js
const scores = [
{ name: 'Asabeneh', score: 95 },
{ name: 'Mathias', score: 80 },
@ -281,56 +354,81 @@ const scores = [
{ name: 'John', score: 100 }
]
const scoresGreaterEight = scores.filter((score) => score.score > 80)
console.log(scoresGreaterEight) //[{name: 'Asabeneh', score: 95}, {name: 'Martha', score: 85},{name: 'John', score: 100}]
const scoresGreaterEight = scores.filter(score => score.score > 80)
console.log(scoresGreaterEight)
```
```sh
[{name: 'Asabeneh', score: 95}, {name: 'Martha', score: 85},{name: 'John', score: 100}]
```
### reduce
*reduce*: Reduce takes a callback function. The call back function takes accumulator and current value as a parameter and returns a single value:
_reduce_: Reduce takes a callback function. The call back function takes accumulator and current value as a parameter and returns a single value:
```js
const numbers = [1,2,3,4,5];
const sum = numbers.reduce((accum, curr)=> accum + curr)
const numbers = [1, 2, 3, 4, 5]
const sum = numbers.reduce((accum, curr) => accum + curr)
console.log(sum)
```
console.log(sum) //15
```js
15
```
### every
*every*: Check if all the elements are similar in one aspect. It returns boolean
_every_: Check if all the elements are similar in one aspect. It returns boolean
```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const areAllStr = names.every((name) => typeof name ==='string');
console.log(arrAllStr) // true;
const areAllStr = names.every(name => typeof name === 'string')
console.log(arrAllStr)
```
```sh
true
```
```js
const areAllTrue = [true, true, true, true]
const areAllTrue = bools.every((b)=> {
return b === true;
const bools = [true, true, true, true]
const areAllTrue = bools.every(b => {
return b === true
})
console.log(areAllTrue) //true
```
```sh
true
```
### find
*find*: Return the first element which satisfies the condition
_find_: Return the first element which satisfies the condition
```js
const ages = [24, 22, 25, 32, 35, 18]
const age = ages.find(age => age < 20)
const ages = [24, 22,25,32,35,18];
const age = ages.find((age) => age < 20)
console.log(age) // 18
console.log(age)
```
```js
18
```
```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const result = names.find(name => name.length > 7)
console.log(result) // Asabeneh
const result = names.find(name => name.length > 7)
console.log(result)
```
```sh
Asabeneh
```
```js
@ -342,50 +440,55 @@ const scores = [
{ name: 'John', score: 100 }
]
const score = scores.find((user) => {
const score = scores.find(user => {
return user.score > 80
})
console.log(score) // { name: "Asabeneh", score: 95 }
console.log(score)
```
### some
```sh
{ name: "Asabeneh", score: 95 }
```
*some*: Check if some of the elements are similar in one aspect. It returns boolean
### findIndex
_findIndex_: Return the position of the first element which satisfies the condition
```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const bools = [true, true, true, true]
const areSomeTrue = bools.some((b)=> {
return b === true;
})
const ages = [24, 22, 25, 32, 35, 18]
console.log(areSomeTrue) //true
```
const result = names.findIndex(name => name.length > 7)
console.log(result) // 0
```js
const areAllStr = names.some((name) => typeof name ==='number');
console.log(areAllStr ) // false
const age = ages.findIndex(age => age < 20)
console.log(age) // 5
```
### findIndex
### some
*findIndex*: Return the position of the first element which satisfies the condition
_some_: Check if some of the elements are similar in one aspect. It returns boolean
```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const ages = [24, 22,25,32,35,18]
const bools = [true, true, true, true]
const result = names.findIndex(name => name.length > 7)
console.log(result) // 0
const areSomeTrue = bools.some(b => {
return b === true
})
const age = ages.findIndex((age) => age < 20)
console.log(age) // 5
console.log(areSomeTrue) //true
```
```js
const areAllStr = names.some(name => typeof name === 'number')
console.log(areAllStr) // false
```
### sort
*sort*: The sort methods arranges the array elements either ascending or descending order. By default, the ***sort()*** method sorts values as strings.This works well for string array items but not for numbers. If number values are sorted as strings and it give us wrong result. Sort method modify the original array. It is recommended to copy the original document before you start sorting.
_sort_: The sort methods arranges the array elements either ascending or descending order. By default, the **_sort()_** method sorts values as strings.This works well for string array items but not for numbers. If number values are sorted as strings and it give us wrong result. Sort method modify the original array. It is recommended to copy the original data before you start using _sort_ method.
#### Sorting string values
@ -395,21 +498,22 @@ console.log(products.sort()) // ['Apple', 'Carrot', 'Coffee', 'Honey', 'Milk', '
//Now the original products array is also sorted
```
#### Sorting Numeric values
#### Sorting Numeric values
As you can see in the example below, 100 came first after sorted in ascending order. Sort converts items to string , since '100' and other numbers compared, 1 which the beginning of the string '100' became the smallest. To avoid this, we use a compare call back function inside the sort method, which return a negative, zero or positive.
As you can see in the example below, 100 came first after sorted in ascending order. Sort converts items to string , since '100' and other numbers compared, 1 which the beginning of the string '100' became the smallest. To avoid this, we use a compare call back function inside the sort method, which return a negative, zero or positive.
```js
const numbers = [9.81, 3.14, 100, 37]
// Using sort method to sort number items provide a wrong result. see below
console.log(numbers.sort()) //[100, 3.14, 37, 9.81]
numbers.sort(function(a, b) {
return a - b
return a - b
})
console.log(numbers) // [3.14, 9.81, 37, 100]
numbers.sort(function(a, b) {
return b - a
return b - a
})
console.log(numbers) //[100, 37, 9.81, 3.14]
```
@ -422,35 +526,43 @@ When ever we sort objects in an array. We use the object key to compare. Lets se
objArr.sort(function(a, b) {
if (a.key < b.key) return -1
if (a.key > b.key) return 1
return 0;
return 0
})
// or
objArr.sort(function(a, b) {
if (a['key'] < b['key']) return -1;
if (a['key'] > b['key']) return 1;
return 0;
if (a['key'] < b['key']) return -1
if (a['key'] > b['key']) return 1
return 0
})
const users = [{name:'Asabeneh', age:150}, {name:'Brook', age:50}, {name:'Eyo', age:100},{name:'Elias', age:22}];
const users = [
{ name: 'Asabeneh', age: 150 },
{ name: 'Brook', age: 50 },
{ name: 'Eyo', age: 100 },
{ name: 'Elias', age: 22 }
]
users.sort((a, b) => {
if (a.age < b.age) return -1;
if (a.age > b.age) return 1;
return 0;
});
console.log(users); // sorted ascending
if (a.age < b.age) return -1
if (a.age > b.age) return 1
return 0
})
console.log(users) // sorted ascending
//[{…}, {…}, {…}, {…}]
```
🌕 You are doing great.Never give up because great things take time. You have just completed day 9 challenges and you are 9 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
🌕 You are doing great.Never give up because great things take time. You have just completed day 9 challenges and you are 9 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## 💻 Exercises
### Exercises: Level 1
```js
const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'IceLand'];
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'];
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const products = [
const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'IceLand']
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const products = [
{ product: 'banana', price: 3 },
{ product: 'mango', price: 6 },
{ product: 'potato', price: ' ' },
@ -460,41 +572,47 @@ console.log(users); // sorted ascending
]
```
1. Explain the difference between ***forEach, map, filter, and reduce***.
1. Explain the difference between **_forEach, map, filter, and reduce_**.
2. Define a call function before you them in forEach, map, filter or reduce.
3. Use ***forEach*** to console.log each country in the countries array.
4. Use ***forEach*** to console.log each name in the names array.
5. Use ***forEach*** to console.log each number in the numbers array.
6. Use ***map*** to create a new array by changing each country to uppercase in the countries array.
7. Use ***map*** to create an array of countries length from countries array.
8. Use ***map*** to create a new array by changing each number to square in the numbers array
9. Use ***map*** to change to each name to uppercase in the names array
10. Use ***map*** to map the products array to its corresponding prices.
11. Use ***filter*** to filter out countries containing ***land***.
12. Use ***filter*** to filter out countries having six character.
13. Use ***filter*** to filter out countries containing six letters and more in the country array.
14. Use ***filter*** to filter out country start with 'E';
15. Use ***filter*** to filter out only prices with values.
16. Find the total price of products by chaining two or more array iterators(eg. arr.map(callback).filter(callback).reduce(callback))
17. Find the sum of price of products using only reduce reduce(callback))
3. Use **_forEach_** to console.log each country in the countries array.
4. Use **_forEach_** to console.log each name in the names array.
5. Use **_forEach_** to console.log each number in the numbers array.
6. Use **_map_** to create a new array by changing each country to uppercase in the countries array.
7. Use **_map_** to create an array of countries length from countries array.
8. Use **_map_** to create a new array by changing each number to square in the numbers array
9. Use **_map_** to change to each name to uppercase in the names array
10. Use **_map_** to map the products array to its corresponding prices.
11. Use **_filter_** to filter out countries containing **_land_**.
12. Use **_filter_** to filter out countries having six character.
13. Use **_filter_** to filter out countries containing six letters and more in the country array.
14. Use **_filter_** to filter out country start with 'E';
15. Use **_filter_** to filter out only prices with values.
18. Declare a function called getStringLists which takes an array as a parameter and then returns an array only with string items.
19. Use ***reduce*** to sum all the numbers in the numbers array.
20. Use ***reduce*** to concatenate all the countries and to produce this sentence: ***Estonia, Finland, Sweden, Denmark, Norway, and IceLand are north European countries***
21. Explain the difference between ***some*** and ***every***
22. Use ***some*** to check if some names' length greater than seven in names array
23. Use ***every*** to check if all the countries contain the word land
24. Explain the difference between ***find*** and ***findIndex***.
25. Use ***find*** to find the first country containing only six letters in the countries array
26. Use ***findIndex*** to find the position of the first country containing only six letters in the countries array
27. Use ***findIndex*** to find the position of ***Norway*** if it doesn't exist in the array you will get -1.
28. Use ***findIndex*** to find the position of ***Russia*** if it doesn't exist in the array you will get -1.
29. Declare a function called ***categorizeCountries*** which returns an array of countries which have some common pattern(you find the countries array in this repository as countries.js(eg 'land', 'ia', 'island','stan')).
30. Create a function which return an array of objects, which is the letter and the number of times the letter use to start with a name of a country.
31. Declare a ***getFirstTenCountries*** function and return an array of ten countries. Use different functional programming to work on the countries.js array
32. Declare a ***getLastTenCountries*** function which which returns the last ten countries in the countries array.
33. Find out which *letter* is used many *times* as initial for a country name from the countries array (eg. Finland, Fiji, France etc)
34. Use the countries information, in the data folder. Sort countries by name, by capital, by population
35. \*\*\* Find the 10 most spoken languages:
19. Use **_reduce_** to sum all the numbers in the numbers array.
20. Use **_reduce_** to concatenate all the countries and to produce this sentence: **_Estonia, Finland, Sweden, Denmark, Norway, and IceLand are north European countries_**
21. Explain the difference between **_some_** and **_every_**
22. Use **_some_** to check if some names' length greater than seven in names array
23. Use **_every_** to check if all the countries contain the word land
24. Explain the difference between **_find_** and **_findIndex_**.
25. Use **_find_** to find the first country containing only six letters in the countries array
26. Use **_findIndex_** to find the position of the first country containing only six letters in the countries array
27. Use **_findIndex_** to find the position of **_Norway_** if it doesn't exist in the array you will get -1.
28. Use **_findIndex_** to find the position of **_Russia_** if it doesn't exist in the array you will get -1.
### Exercises: Level 2
1. Find the total price of products by chaining two or more array iterators(eg. arr.map(callback).filter(callback).reduce(callback))
1. Find the sum of price of products using only reduce reduce(callback))
1. Declare a function called **_categorizeCountries_** which returns an array of countries which have some common pattern(you find the countries array in this repository as countries.js(eg 'land', 'ia', 'island','stan')).
1. Create a function which return an array of objects, which is the letter and the number of times the letter use to start with a name of a country.
1. Declare a **_getFirstTenCountries_** function and return an array of ten countries. Use different functional programming to work on the countries.js array
1. Declare a **_getLastTenCountries_** function which which returns the last ten countries in the countries array.
1. Find out which _letter_ is used many _times_ as initial for a country name from the countries array (eg. Finland, Fiji, France etc)
### Exercises: Level 3
1. Use the countries information, in the data folder. Sort countries by name, by capital, by population
1. \*\*\* Find the 10 most spoken languages:
````js
// Your output should look like this
@ -519,67 +637,68 @@ console.log(users); // sorted ascending
(25, 'Arabic')
]```
36. \*\*\* Use countries_data.js file create a function which create the ten most populated countries
````js
console.log(mostPopulatedCountries(countries, 10))
[
{country: 'China', population: 1377422166},
{country: 'India', population: 1295210000},
{country: 'United States of America', population: 323947000},
{country: 'Indonesia', population: 258705000},
{country: 'Brazil', population: 206135893},
{country: 'Pakistan', population: 194125062},
{country: 'Nigeria', population: 186988000},
{country: 'Bangladesh', population: 161006790},
{country: 'Russian Federation', population: 146599183},
{country: 'Japan', population: 126960000}
]
console.log(mostPopulatedCountries(countries, 3))
[
{country: 'China', population: 1377422166},
{country: 'India', population: 1295210000},
{country: 'United States of America', population: 323947000}
]```
````
37. \*\*\* Try to develop a program which calculate measure of central tendency of a sample(mean, median, mode) and measure of variability(range, variance, standard deviation). In addition to those measures find the min, max, count, percentile, and frequency distribution of the sample. You can create an object called statistics and create all the functions which do statistical calculations as method for the statistics object. Check the output below.
```js
const ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26]
console.log('Count:', statistics.count()) // 25
console.log('Sum: ', statistics.sum()) // 744
console.log('Min: ', statistics.min()) // 24
console.log('Max: ', statistics.max()) // 38
console.log('Range: ', statistics.range() // 14
console.log('Mean: ', statistics.mean()) // 30
console.log('Median: ',statistics.median()) // 29
console.log('Mode: ', statistics.mode()) // {'mode': 26, 'count': 5}
console.log('Variance: ',statistics.var()) // 17.5
console.log('Standard Deviation: ', statistics.std()) // 4.2
console.log('Variance: ',statistics.var()) // 17.5
console.log('Frequency Distribution: ',statistics.freqDist()) # [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
```
```sh
console.log(statistics.describe())
Count: 25
Sum: 744
Min: 24
Max: 38
Range: 14
Mean: 30
Median: 29
Mode: (26, 5)
Variance: 17.5
Standard Deviation: 4.2
Frequency Distribution: [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
```
````
1. \*\*\* Use countries_data.js file create a function which create the ten most populated countries
````js
console.log(mostPopulatedCountries(countries, 10))
[
{country: 'China', population: 1377422166},
{country: 'India', population: 1295210000},
{country: 'United States of America', population: 323947000},
{country: 'Indonesia', population: 258705000},
{country: 'Brazil', population: 206135893},
{country: 'Pakistan', population: 194125062},
{country: 'Nigeria', population: 186988000},
{country: 'Bangladesh', population: 161006790},
{country: 'Russian Federation', population: 146599183},
{country: 'Japan', population: 126960000}
]
console.log(mostPopulatedCountries(countries, 3))
[
{country: 'China', population: 1377422166},
{country: 'India', population: 1295210000},
{country: 'United States of America', population: 323947000}
]
```
1. \*\*\* Try to develop a program which calculate measure of central tendency of a sample(mean, median, mode) and measure of variability(range, variance, standard deviation). In addition to those measures find the min, max, count, percentile, and frequency distribution of the sample. You can create an object called statistics and create all the functions which do statistical calculations as method for the statistics object. Check the output below.
```js
const ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26]
console.log('Count:', statistics.count()) // 25
console.log('Sum: ', statistics.sum()) // 744
console.log('Min: ', statistics.min()) // 24
console.log('Max: ', statistics.max()) // 38
console.log('Range: ', statistics.range() // 14
console.log('Mean: ', statistics.mean()) // 30
console.log('Median: ',statistics.median()) // 29
console.log('Mode: ', statistics.mode()) // {'mode': 26, 'count': 5}
console.log('Variance: ',statistics.var()) // 17.5
console.log('Standard Deviation: ', statistics.std()) // 4.2
console.log('Variance: ',statistics.var()) // 17.5
console.log('Frequency Distribution: ',statistics.freqDist()) # [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
```
```sh
console.log(statistics.describe())
Count: 25
Sum: 744
Min: 24
Max: 38
Range: 14
Mean: 30
Median: 29
Mode: (26, 5)
Variance: 17.5
Standard Deviation: 4.2
Frequency Distribution: [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
```
🎉 CONGRATULATIONS ! 🎉
[<< Day 8](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/08_Day/08_day_objects.md) | [Day 10 >>](#)
[<< Day 8](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/08_Day/08_day_objects.md) | [Day 10 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/10_Day/10_day_Set_and_Map.md)

@ -0,0 +1,441 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> January, 2020</small>
</sub>
</div>
[<< Day 9](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/09_Day/09_day_higher_order_functions.md) | [Day 11>>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/11_Day/11_destructuring_and_spread.md)
![Day 10](../images/banners/day_1_10.png)
- [Day 10](#day-10)
- [Set](#set)
- [Creating an empty set](#creating-an-empty-set)
- [Creating set from array](#creating-set-from-array)
- [Adding an element to a set](#adding-an-element-to-a-set)
- [Deleting an element a set](#deleting-an-element-a-set)
- [Checking an element in the set](#checking-an-element-in-the-set)
- [Clearing the set](#clearing-the-set)
- [Union of sets](#union-of-sets)
- [Intersection of sets](#intersection-of-sets)
- [Difference of sets](#difference-of-sets)
- [Map](#map)
- [Creating an empty Map](#creating-an-empty-map)
- [Creating an Map from array](#creating-an-map-from-array)
- [Adding values to the Map](#adding-values-to-the-map)
- [Getting a value from Map](#getting-a-value-from-map)
- [Checking key in Map](#checking-key-in-map)
- [Exercises](#exercises)
- [Exercises:Level 1](#exerciseslevel-1)
- [Exercises:Level 2](#exerciseslevel-2)
- [Exercises:Level 3](#exerciseslevel-3)
# Day 10
## Set
Set is a collection a collection of elements. Set can only contains unique elements.
Lets see how to create a set
### Creating an empty set
```js
const companies = new Set()
console.log(companies)
```
```sh
{}
```
### Creating set from array
```js
const languages = [
'English',
'Finnish',
'English',
'French',
'Spanish',
'English',
'French'
]
const setOfLangauges = new Set(languages)
console.log(setOfLangauges)
```
```sh
Set(4) {"English", "Finnish", "French", "Spanish"}
```
Set is an iterable object and we can iterate through each elements.
```js
const languages = [
'English',
'Finnish',
'English',
'French',
'Spanish',
'English',
'French'
]
const setOfLangauges = new Set(languages)
for (const language of setOfLangauges) {
console.log(language)
}
```
```sh
English
Finnish
French
Spanish
```
### Adding an element to a set
```js
const companies = new Set() // creating an empty set
console.log(companies.size) // 0
companies.add('Google') // add element to the set
companies.add('Facebook')
companies.add('Amazon')
companies.add('Oracle')
companies.add('Microsoft')
console.log(companies.size) // 5 elements in the set
console.log(companies)
```
```sh
Set(5) {"Google", "Facebook", "Amazon", "Oracle", "Microsoft"}
```
We can also use loop to add element to a set.
```js
const companies = ['Google', 'Facebook', 'Amazon', 'Oracle', 'Microsoft']
setOfCompanies = new Set()
for (const company of companies) {
setOfCompanies.add(company)
}
```
```sh
Set(5) {"Google", "Facebook", "Amazon", "Oracle", "Microsoft"}
```
### Deleting an element a set
We can delete an element from a set using a delete method.
```js
console.log(companies.delete('Google'))
console.log(companies.size) // 4 elements left in the set
```
### Checking an element in the set
The has method can help to know if a certain element exists in a set.
```js
console.log(companies.has('Apple')) // false
console.log(companies.has('Facebook')) // true
```
### Clearing the set
It removes all the elements from a set.
```js
companies.clear()
console.log(companies)
```
```sh
{}
```
See the example below to learn how to use set.
```js
const languages = [
'English',
'Finnish',
'English',
'French',
'Spanish',
'English',
'French'
]
const langSet = new Set(languages)
console.log(langSet) // Set(4) {"English", "Finnish", "French", "Spanish"}
console.log(langSet.size) // 4
const counts = []
const count = {}
for (const l of langSet) {
const filteredLang = languages.filter(lng => lng === l)
console.log(filteredLang) // ["English", "English", "English"]
counts.push({ lang: l, count: filteredLang.length })
}
console.log(counts)
```
```js
[
{ lang: 'English', count: 3 },
{ lang: 'Finnish', count: 1 },
{ lang: 'French', count: 2 },
{ lang: 'Spanish', count: 1 }
]
```
Other use case of set. For instance to count unique item in an array.
```js
const numbers = [5, 3, 2, 5, 5, 9, 4, 5]
const setOfNumbers = new Set(numbers)
console.log(setOfNumbers)
```
```sh
Set(5) {5, 3, 2, 9, 4}
```
### Union of sets
To find a union to two sets can be achieved using spread operator. Lets find the union of set A and set B (A U B)
```js
let a = [1, 2, 3, 4, 5]
let b = [3, 4, 5, 6]
let c = [...a, ...b]
let A = new Set(a)
let B = new Set(b)
let C = new Set(c)
console.log(C)
```
```sh
Set(6) {1, 2, 3, 4, 5,6}
```
### Intersection of sets
To find an intersection of two sets can be achieved using filter. Lets find the union of set A and set B (A ∩ B)
```js
let a = [1, 2, 3, 4, 5]
let b = [3, 4, 5, 6]
let A = new Set(a)
let B = new Set(b)
let c = a.filter(num => B.has(num))
let C = new Set(c)
console.log(C)
```
```sh
Set(3) {3, 4, 5}
```
### Difference of sets
To find an the difference between two sets can be achieved using filter. Lets find the different of set A and set B (A \ B)
```js
let a = [1, 2, 3, 4, 5]
let b = [3, 4, 5, 6]
let A = new Set(a)
let B = new Set(b)
let c = a.filter(num => !B.has(num))
let C = new Set(c)
console.log(C)
```
```sh
Set(2) {1, 2}
```
## Map
### Creating an empty Map
```js
const map = new Map()
console.log(map)
```
```sh
Map(0) {}
```
### Creating an Map from array
```js
countries = [
['Finland', 'Helsinki'],
['Sweden', 'Stockholm'],
['Norway', 'Oslo']
]
const map = new Map(countries)
console.log(map)
console.log(map.size)
```
```sh
Map(3) {"Finland" => "Helsinki", "Sweden" => "Stockholm", "Norway" => "Oslo"}
3
```
### Adding values to the Map
```js
const countriesMap = new Map()
console.log(countriesMap.size) // 0
countriesMap.set('Finland', 'Helsinki')
countriesMap.set('Sweden', 'Stockholm')
countriesMap.set('Norway', 'Oslo')
console.log(countriesMap)
console.log(countriesMap.size)
```
```sh
Map(3) {"Finland" => "Helsinki", "Sweden" => "Stockholm", "Norway" => "Oslo"}
3
```
### Getting a value from Map
```js
console.log(countriesMap.get('Finland'))
```
```sh
Helsinki
```
### Checking key in Map
Check if a key exist in a map using *has* method. It returns *true* or *false*.
```js
console.log(countriesMap.has('Finland'))
```
```sh
true
```
Getting all values from map using loop
```js
for (const country of countriesMap) {
console.log(country)
}
```
```sh
(2) ["Finland", "Helsinki"]
(2) ["Sweden", "Stockholm"]
(2) ["Norway", "Oslo"]
```
```sh
for (const [country, city] of countriesMap){
console.log(country, city)
}
```
```sh
Finland Helsinki
Sweden Stockholm
Norway Oslo
```
🌕 You established a big milestone, you are unstoppable. Keep going! You have just completed day 10 challenges and you are 10 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## Exercises
### Exercises:Level 1
```js
const a = {4, 5, 8, 9}
const b = {3, 4, 5, 7}
const countries = ['Finland', 'Sweden', 'Norway']
```
1. create an empty set
2. Create a set containing 0 to 10 using loop
3. Remove an element from a set
4. Clear a set
5. Create a set of 5 string elements from array
6. Create a map of countries and number of characters of a country
### Exercises:Level 2
1. Find a union b
2. Find a intersection b
3. Find a with b
### Exercises:Level 3
1. \*\*\* Use the countries data to find the 10 most spoken languages:
````js
// Your output should look like this
console.log(mostSpokenLanguages(countries, 10))
[(91, 'English'),
(45, 'French'),
(25, 'Arabic'),
(24, 'Spanish'),
(9, 'Russian'),
(9, 'Portuguese'),
(8, 'Dutch'),
(7, 'German'),
(5, 'Chinese'),
(4, 'Swahili'),
(4, 'Serbian')]
// Your output should look like this
console.log(mostSpokenLanguages(countries, 3))
[
(91, 'English'),
(45, 'French'),
(25, 'Arabic')
]```
````
🎉 CONGRATULATIONS ! 🎉
[<< Day 9](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/09_Day/09_day_higher_order_functions.md) | [Day 11>>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/11_Day/11_destructuring_and_spread.md)

@ -0,0 +1,693 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> January, 2020</small>
</sub>
</div>
[<< Day 10](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/09_Day/09_day_Set_and_Map.md) | [Day 12>>](#)
![Day 11](../images/banners/day_1_11.png)
- [Day 11](#day-11)
- [Destructuring and Spread](#destructuring-and-spread)
- [Destructing Arrays](#destructing-arrays)
- [Destructuring during iteration](#destructuring-during-iteration)
- [Destructuring Object](#destructuring-object)
- [Renaming during structuring](#renaming-during-structuring)
- [Object parameter without destructuring](#object-parameter-without-destructuring)
- [Object parameter with destructuring](#object-parameter-with-destructuring)
- [Destructuring object during iteration](#destructuring-object-during-iteration)
- [Spread or Rest Operator](#spread-or-rest-operator)
- [Spread operator to get the rest of array elements](#spread-operator-to-get-the-rest-of-array-elements)
- [Spread operator to copy array](#spread-operator-to-copy-array)
- [Spread operator to copy object](#spread-operator-to-copy-object)
- [Spread operator with arrow function](#spread-operator-with-arrow-function)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Day 11
## Destructuring and Spread
Destructuring is a way to unpack arrays, and objects and assigning to a distinct variable.
### Destructing Arrays
```js
const numbers = [1, 2, 3]
let [numOne, numTwo, numThree] = numbers
console.log(numOne, numTwo, numThree)
```
```sh
1 2 3
```
```js
const names = ['Asabeneh', 'Brook', 'David', 'John']
let [firstPerson, secondPerson, ThirdPerson, fourth Person] = names
console.log(firstName, secondPerson,thirdPerson, fourthPerson)
```
```sh
Asabeneh Brook David John
```
```js
const scientificConstants = [2.72, 3.14, 9.81, 37, 100]
let [e, pi, gravity, bodyTemp, boilingTemp] = scientificConstants
console.log(e,pi,gravity, bodyTemp, boilingTemp)
```
```sh
2.72 3.14 9.81 37 100
```
```js
const fullStack = [
['HTML', 'CSS', 'JS', 'React'],
['Node', 'Express', 'MongoDB']
]
const [frontEnd, backEnd] = fullStack
console.log(frontEnd)
console.log(backEnd)
```
```sh
["HTML", "CSS", "JS", "React"]
["Node", "Express", "MongoDB"]
```
If we like to skip on of the values in the array we use additional comma. The comma helps to omit the value at that specific index
```js
const numbers = [1, 2, 3]
let [numOne, , numThree] = numbers //2 is omitted
console.log(numOne, numThree)
```
```sh
1 3
```
```js
const names = ['Asabeneh', 'Brook', 'David', 'John']
let [, secondPerson, , fourth Person] = name // first and third person is omitted
console.log(secondPerson, fourthPerson)
```
```sh
Brook John
```
We can use default value in case the value of array for that index is undefined:
```js
const names = [undefined, 'Brook', 'David']
let [
firstPerson = 'Asabeneh',
secondPerson,
thirdPerson,
fourthPerson = 'John'
] = names
console.log(firstPerson, secondPerson, thirdPerson, fourthPerson)
```
```sh
Asabeneh Brook David John
```
We can not assign variable to all the elements in the array. We can destructure few of the first and we can get the remaining as array using spread operator(...).
```js
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let [num1, num2, num3, ...rest] = nums
console.log(num1, num2, num3)
console.log(rest)
```
```sh
1 2 3
[4, 5, 6, 7, 8, 9, 10]
```
### Destructuring during iteration
```js
const countries = [['Finland', 'Helsinki'], ['Sweden', 'Stockholm'], ['Norway', 'Oslo']]
for (const [country, city] of countries) {
console.log(country, city)
}
```
```sh
Finland Helsinki
Sweden Stockholm
Norway Oslo
```
```js
const fullStack = [
['HTML', 'CSS', 'JS', 'React'],
['Node', 'Express', 'MongoDB']
]
for(const [first, second, third] of fullStack) {
console.log(first, second, third)
}
```
```sh
HTML CSS JS
Node Express MongoDB
```
### Destructuring Object
When we destructure the name of the variable we use to destructure should be exactly the same as the key or property of the object. See the example below.
```js
const rectangle = {
width: 20,
height: 10,
area: 200
}
let { width, height, area, perimeter } = rectangle
console.log(width, height, area, perimeter)
```
```sh
20 10 200 undefined
```
### Renaming during structuring
```js
const rectangle = {
width: 20,
height: 10,
area: 200
}
let { width: w, heigh: h, area: a, perimeter: p } = rectangle
console.log(w, h, a, p)
```
```sh
20 10 200 undefined
```
If the key is not found in the object the variable will be assigned to undefined. In case, the key is not in the object we can give a default value during declaration. See the example.
```js
const rectangle = {
width: 20,
height: 10,
area: 200
}
let { width, heigh, area, perimeter = 60 } = rectangle
console.log(width, height, area, perimeter) //20 10 200 60
//Lets modify the object:width to 30 and perimeter to 80
```
```js
const rectangle = {
width: 30,
height: 10,
area: 200,
perimeter: 80
}
let { width, heigh, area, perimeter = 60 } = rectangle
console.log(width, height, area, perimeter) //20 10 200 80
```
Destructuring keys as a function parameters. Lets create a function which take a rectangle object and it return a perimeter of a rectangle.
### Object parameter without destructuring
```js
// Without destructuring
const rect = {
width: 20,
height: 10
}
const calculatePerimeter = rectangle => {
return 2 * (rectangle.width + rectangle.height)
}
console.log(calculatePerimeter(rect)) // 60
//with destructuring
```
```js
//Another Example
const person = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
age: 250,
country: 'Finland',
job: 'Instructor and Developer',
skills: [
'HTML',
'CSS',
'JavaScript',
'React',
'Redux',
'Node',
'MongoDB',
'Python',
'D3.js'
],
languages: ['Amharic', 'English', 'Suomi(Finnish)']
}
// Lets create a function which give information about the person object without destructuring
const getPersonInfo = obj => {
const skills = obj.skills
const formattedSkills = skills.slice(0, -1).join(', ')
const languages = obj.languages
const formattedLanguages = languages.slice(0, -1).join(', ')
personInfo = `${obj.firstName} ${obj.lastName} lives in ${obj.country}. He is ${
obj.age
} years old. He is an ${obj.job}. He teaches ${formattedSkills} and ${
skills[skills.length - 1]
}. He speaks ${formattedLanguages} and a little bit of ${languages[2]}.`
return personInfo
}
console.log(getPersonInfo(person))
```
### Object parameter with destructuring
```js
const calculatePerimeter = ({ width, height }) => {
return 2 * (width + height)
}
console.log(calculatePerimeter(rect)) // 60
```
```js
// Lets create a function which give information about the person object with destructuring
const getPersonInfo = ({
firstName,
lastName,
age,
country,
job,
skills,
languages
}) => {
const formattedSkills = skills.slice(0, -1).join(', ')
const formattedLanguages = languages.slice(0, -1).join(', ')
personInfo = `${firstName} ${lastName} lives in ${country}. He is ${age} years old. He is an ${job}. He teaches ${formattedSkills} and ${
skills[skills.length - 1]
}. He speaks ${formattedLanguages} and a little bit of ${languages[2]}.`
return personInfo
}
console.log(getPersonInfo(person))
/*
Asabeneh Yetayeh lives in Finland. He is 200 years old. He is an Instructor and Developer. He teaches HTML, CSS, JavaScript, React, Redux, Node, MongoDB, Python and D3.js. He speaks Amharic, English and a little bit of Suomi(Finnish)
*/
```
### Destructuring object during iteration
```js
const todoList = [
{
task:'Prepare JS Test',
time:'4/1/2020 8:30',
completed:true
},
{
task:'Give JS Test',
time:'4/1/2020 10:00',
completed:false
},
{
task:'Assess Test Result',
time:'4/1/2020 1:00',
completed:false
}
]
for (const {task, time, completed} of todoList){
console.log(task, time, completed)
}
```
```sh
Prepare JS Test 4/1/2020 8:30 true
Give JS Test 4/1/2020 10:00 false
Assess Test Result 4/1/2020 1:00 false
```
### Spread or Rest Operator
When we destructure an array we use the spread operator(...) to get the rest elements as array. In addition to that we use spread operator to spread arr elements to another array.
### Spread operator to get the rest of array elements
```js
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let [num1, num2, num3, ...rest] = nums
console.log(num1, num2, num3)
console.log(rest)
```
```sh
1 2 3
[4, 5, 6, 7, 8, 9, 10]
```
```js
const countries = [
'Germany',
'France',
'Belgium',
'Finland',
'Sweden',
'Norway',
'Denmark',
'Iceland'
]
let [gem, fra, , ...nordicCountries] = countries
console.log(gem)
console.log(fra)
console.log(nordicCountries)
```
```sh
Germany
France
["Finland", "Sweden", "Norway", "Denmark", "Iceland"]
```
### Spread operator to copy array
```js
const evens = [0, 2, 4, 6, 8, 10]
const evenNumbers = [...evens]
const odds = [1, 3, 5, 7, 9]
const oddNumbers = [...odds]
const wholeNumbers = [...evens, ...odds]
console.log(evenNumbers)
console.log(oddNumbers)
console.log(wholeNumbers)
```
```sh
[0, 2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]
[0, 2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
```
```js
const frontEnd = ['HTML', 'CSS', 'JS', 'React']
const backEnd = ['Node', 'Express', 'MongoDB']
const fullStack = [...frontEnd, ...backEnd]
console.log(fullStack)
```
```sh
["HTML", "CSS", "JS", "React", "Node", "Express", "MongoDB"]
```
### Spread operator to copy object
We can copy an object using a spread operator
```js
const user = {
name:'Asabeneh',
title:'Programmer',
country:'Finland',
city:'Helsinki'
}
const copiedUser = {...user}
console.log(copiedUser)
```
```sh
{name: "Asabeneh", title: "Programmer", country: "Finland", city: "Helsinki"}
```
Modifying or changing the object while copying
```js
const user = {
name:'Asabeneh',
title:'Programmer',
country:'Finland',
city:'Helsinki'
}
const copiedUser = {...user, title:'instructor'}
console.log(copiedUser)
```
```sh
{name: "Asabeneh", title: "instructor", country: "Finland", city: "Helsinki"}
```
#### Spread operator with arrow function
Whenever we like to write an arrow function which takes unlimited number of arguments we use a spread operator. If we use a spread operator as a parameter, the argument passed when we invoke a function will change to an array.
```js
const sumAllNums = (...args) => {
console.log(args)
}
sumAllNums(1, 2, 3,4,5)
```
```sh
[1, 2, 3, 4, 5]
```
```js
const sumAllNums = (...args) => {
let sum = 0
for (const num of args){
sum += num
}
return sum
}
console.log(sumAllNums(1, 2, 3,4,5))
```
```sh
15
```
🌕 You achieved quite a lot so far. Now, your level of JavaScript is upper intermediate. Keep going! You have just completed day 11 challenges and you are 11 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## Exercises
### Exercises: Level 1
```js
const constants = [2.72, 3.14, 9.81, 37, 100]
const countries = ['Finland', 'Estonia', 'Sweden', 'Denmark', 'Norway']
const rectangle = {
width: 20,
height: 10,
area: 200,
perimeter: 60
}
const users = [
{
name:'Brook',
scores:75,
skills:['HTM', 'CSS', 'JS'],
age:16
},
{
name:'Alex',
scores:80,
skills:['HTM', 'CSS', 'JS'],
age:18
},
{
name:'David',
scores:75,
skills:['HTM', 'CSS'],
age:22
},
{
name:'John',
scores:85,
skills:['HTML'],
age:25
},
{
name:'Sara',
scores:95,
skills:['HTM', 'CSS', 'JS'],
age: 26
},
{
name:'Martha',
scores:80,
skills:['HTM', 'CSS', 'JS'],
age:18
},
{
name:'Thomas',
scores:90,
skills:['HTM', 'CSS', 'JS'],
age:20
}
]
```
1. Destructure and assign the elements of constants array to e, pi, gravity, humanBodyTemp, waterBoilingTemp.
2. Destructure and assign the elements of countries array to fin, est, sw, den, nor
3. Destructure the rectangle object by its properties or keys.
### Exercises: Level 2
1. Iterate through the users array and get all the keys of the object using destructuring
2. Find the persons who have less than two skills
### Exercises: Level 3
1. Destructure the countries object print name, capital, population and languages of all countries
2. A junior developer structure student name, skills and score in array of arrays which may not easy to read. Destruction the following array name to name, skills array to skills, scores array to scores, JavaScript score to jsScore and React score to reactScore variable.
```js
const student = ['David', ['HTM', 'CSS', 'JS', 'React'], [98, 85, 90, 95]]
console.log(name, skills, scores, jsScore, reactScore)
```
3. Write a function called *convertArrayToObject* which can convert the array to a structure object.
```js
const students = [
['David', ['HTM', 'CSS', 'JS', 'React'], [98, 85, 90, 95]],
['John', ['HTM', 'CSS', 'JS', 'React'], [85, 80, 85, 80]]
]
console.log(convertArrayToObject(students))
[
{
name: 'David',
skills: ['HTM','CSS','JS','React'],
scores: [98,85,90,95]
},
{
name: 'John',
skills: ['HTM','CSS','JS','React'],
scores: [85, 80,85,80]
}
]
```
4. Copy the student object to newStudent without mutating the original object. In the new object add the following ?
- Add Bootstrap with level 8 to the front end skill sets
- Add Express with level 9 to the back end skill sets
- Add SQL with level 8 to the data base skill sets
- Add SQL without level to the data science skill sets
```js
const student = {
name: 'David',
age: 25,
skills: {
frontEnd: [
{ skill: 'HTML', level: 10 },
{ skill: 'CSS', level: 8 },
{ skill: 'JS', level: 8 },
{ skill: 'React', level: 9 }
],
backEnd: [
{ skill: 'Node',level: 7 },
{ skill: 'GraphQL', level: 8 },
],
dataBase:[
{ skill: 'MongoDB', level: 7.5 },
],
dataScience:['Python', 'R', 'D3.js']
}
}
```
The copied object output should look like this:
```js
{
name: 'David',
age: 25,
skills: {
frontEnd: [
{skill: 'HTML',level: 10},
{skill: 'CSS',level: 8},
{skill: 'JS',level: 8},
{skill: 'React',level: 9},
{skill: 'BootStrap',level: 8}
],
backEnd: [
{skill: 'Node',level: 7},
{skill: 'GraphQL',level: 8},
{skill: 'Express',level: 9}
],
dataBase: [
{ skill: 'MongoDB',level: 7.5},
{ skill: 'SQL',level: 8}
],
dataScience: ['Python','R','D3.js','SQL']
}
}
🎉 CONGRATULATIONS ! 🎉
[<< Day 10](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/09_Day/09_day_Set_and_Map.md) | [Day 12>>](#)

@ -1,8 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<a class="header-badge" target="_blank" href="https://github.com/Asabeneh/30DaysOfJavaScript">
<img alt="GitHub stars" src="https://img.shields.io/github/stars/asabeneh/30DaysOfJavaScript?style=social">
</a>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
@ -51,7 +48,7 @@
- [Checking Data types](#checking-data-types)
- [Comments](#comments)
- [Variables](#variables)
- [💻 Day 1: Exercises](#-day-1-exercises)
- [💻 Day 1: Exercises](#%f0%9f%92%bb-day-1-exercises)
# 📔Day 1
@ -443,7 +440,7 @@ console.log(firstName); //not defined, because it is not assigned to a value yet
Null in JavaScript means an empty value.
```js
let emptyValue = nulll
let emptyValue = null
```
## Checking Data types
@ -544,17 +541,30 @@ let firstName = 'Asabeneh' // first name of a person
let lastName = 'Yetayeh' // last name of a person
let country = 'Finland' // country
let city = 'Helsinki' // capital city
let age = 100 // age in years
let isMarried = true
let isMarried = true // boolean data type
console.log(firstName, lastName, country, city, age, isMarried)
```
console.log(firstName, lastName, country, city, age, isMarried); //Asabeneh, Yetayeh, Finland, Helsinki, 100, True
```sh
Asabeneh Yetayeh Finland Helsinki 100 True
```
```js
// Declaring variables with number values
let age = 100 // age in years
const gravity = 9.81 // earth gravity in m/s2
const boilingPoint = 100 // water boiling point, temperature in oC
const PI = 3.14 // geometrical constant
console.log(gravity, boilingPoint, PI); // 9.81, 100, 3.14
console.log(gravity, boilingPoint, PI)
```
```sh
9.81 100 3.14
```
```js
// Variables can also be declaring in one line separated by comma
let name = 'Asabeneh', // name of a person
job = 'teacher',
@ -562,6 +572,10 @@ let name = 'Asabeneh', // name of a person
console.log(name, job, live);
```
```sh
Asabeneh teacher Finland
```
When you run the files on 01-Day folder you should get this:
![Day one](./images/day_1.png)

Loading…
Cancel
Save