uploaded exercises files

pull/949/head
Nevzat Atalay 1 year ago
parent dc7cfb9284
commit df2df98d08

@ -1,30 +1,19 @@
# Day 1 - Introduction
# Day 1 - Introdiction
## [Exercise:Solutions](#exercise-solutions)
## [Exercise Level 1](#exercise-level-1)
### [< Home >](../README.md) | [Day 2 >>](./02_day_datatype.md)
### Exercise Level 1
- ### [Exercise Level 1](#exercise-level-1)
#### [Home](../README.md) | [Day 2 >>](./02_day_datatype.md)
1. Write a single line comment which says, _comments can make code readable_
2. Write another single comment which says, _Welcome to 30DaysOfJavaScript_
3. Write a multiline comment which says, _comments can make code readable, easy to reuse_
_and informative_
4. Create a variable.js file and declare variables and assign string, boolean, undefined and null data types
5. Create datatypes.js file and use the JavaScript **_typeof_** operator to check different data types. Check the data type of each variable
6. Declare four variables without assigning values
7. Declare four variables with assigned values
8. Declare variables to store your first name, last name, marital status, country and age in multiple lines
9. Declare variables to store your first name, last name, marital status, country and age in a single line
10. Declare two variables _myAge_ and _yourAge_ and assign them initial values and log to the browser console.
```sh
I am 25 years old.
You are 30 years old.
```
### Exercise Level 1
## Exercise Solutions
### Exercise Level 1
1. Write a single line comment which says, comments can make code readable
@ -117,5 +106,4 @@ let yourAge = 22
console.log("I am " + " " + myAge + " " + "years old.") // I am 25 years old.
console.log("You are" + " " + yourAge + " " + "years old.") // You are 22 years old.
```
### [< Home >](../README.md) | [Day 2 >>](./02_day_datatype.md)
#### [Home](../README.md) | [Day 2 >>](./02_day_datatype.md)

@ -1,87 +1,18 @@
# Day 2 - Datatype
# Exercise Day 2 - DataType
## [Home](../README.md) | [<< Day 1](./01_day_introdiction.md) | [Day 3 >>](./03_day_operators.md)
### [Exercise:Level 1](#exercise-level-1)
1. Declare a variable named challenge and assign it to an initial value **'30 Days Of JavaScript'**.
2. Print the string on the browser console using __console.log()__
3. Print the __length__ of the string on the browser console using _console.log()_
4. Change all the string characters to capital letters using __toUpperCase()__ method
5. Change all the string characters 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. Check if the string contains a word __Script__ using __includes()__ method
9. Split the __string__ into an __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 any 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* and make the result true
22. Use __endsWith()__ method with the string *30 Days Of JavaScript* and make the result true
23. Use __match()__ method to find all the __a__s 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](#exercise-level-2)
## [Exercise:Solutions](#exercise-solutions)
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.
```
2. 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."
```
3. Check if typeof '10' is exactly equal to 10. If not make it exactly equal.
4. Check if parseFloat('9.8') is equal to 10 if not make it exactly equal with 10.
5. Check if 'on' is found in both python and jargon
6. _I hope this course is not full of jargon_. Check if _jargon_ is in the sentence.
7. Generate a random number between 0 and 100 inclusively.
8. Generate a random number between 50 and 100 inclusively.
9. Generate a random number between 0 and 255 inclusively.
10. Access the 'JavaScript' string characters using a random number.
11. 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
```
12. Use __substr__ to slice out the phrase __because because because__ from the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
- ### [Exercise:Level 1](#exercise-level-1)
- ### [Exercise:Level 2](#exercise-level-2)
- ### [Exercise:Level 3](#exercise-level-3) <hr>
### [Exercise:Level 3](#exercise-level-3)
#### [Home](../README.md) | [<< Day 1](./01_day_introdiction.md) | [Day 3 >>](./03_day_operators.md)
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 of all __because__ 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 expressions).
```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'
```
## Exercise Solutions
4. Calculate the total annual income of the person by extracting the numbers from the following text. 'He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month.'
## Exercise Level 1
### Exercise Level 1
1. Declare a variable named challenge and assign it to an initial value '30 Days Of JavaScript'.
```js
@ -452,9 +383,7 @@ console.log(`Annual income is ${montlySalary*12 +
bonus + montlyCourses *12} euro `)
```
## [Home](../README.md) | [<< Day 1](./01_day_introdiction.md) | [Day 3 >>](./03_day_operators.md)
#### [Home](../README.md) | [<< Day 1](./01_day_introdiction.md) | [Day 3 >>](./03_day_operators.md)

@ -1,137 +1,16 @@
# Day 3 - Operators
## [Home](../README.md) | [<< Day 2](./02_day_datatype.md) | [Day 4 >>](./04_day_conditional.md)
## [Exercise:Solutions](#exercise-solutions)
### [Exercise:Level 1](#exercise-level-1)
- ### [Exercise:Level 1](#exercise-level-1)
- ### [Exercise:Level 2](#exercise-level-2)
- ### [Exercise:Level 3](#exercise-level-3) <hr>
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
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.
### [Exercise:Level 2](#exercise-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).
```sh
Enter base: 20
Enter height: 10
The area of the triangle is 100
```
1. Write a script that prompt the user to enter side a, side b, and side c of the triangle and and calculate the perimeter of triangle (perimeter = a + b + c)
```sh
Enter side a: 5
Enter side b: 4
Enter side c: 3
The perimeter of the triangle is 12
```
1. Get length and width using prompt and calculate an area of rectangle (area = length x width and the perimeter of rectangle (perimeter = 2 x (length + width))
1. Get radius using prompt and calculate the area of a circle (area = pi x r x r) and circumference of a circle(c = 2 x pi x r) where pi = 3.14.
1. Calculate the slope, x-intercept and y-intercept of y = 2x -2
1. Slope is m = (y<sub>2</sub>-y<sub>1</sub>)/(x<sub>2</sub>-x<sub>1</sub>). Find the slope between point (2, 2) and point(6,10)
1. Compare the slope of above two questions.
1. Calculate the value of y (y = x<sup>2</sup> + 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 enter hours and rate per hour. Calculate pay of the person?
```sh
Enter hours: 40
Enter rate per hour: 28
Your weekly earning is 1120
```
#### [Home](../README.md) | [<< Day 2](./02_day_datatype.md) | [Day 4 >>](./04_day_conditional.md)
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'
```
```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.
```js
let myAge = 250
let yourAge = 25
```
```sh
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
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 years you live: 100
You lived 3153600000 seconds.
```
1. Create a human readable time format using the Date time object
1. YYYY-MM-DD HH:mm
2. DD-MM-YYYY HH:mm
3. DD/MM/YYYY HH:mm
### [Exercise:Level 3](#exercise-level-3)
1. Create a human readable time format using the Date time object. The hour and the minute should be all the 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
# Exercise Solutions
## Exercise Level 1
@ -474,7 +353,6 @@ console.log(`${year}-${mount}-${day} ${hours} : ${minuts}`)
console.log(`${day}-${mount}-${year} ${hours} : ${minuts}`)
console.log(`${year} / ${mount} / ${day} ${hours} : ${minuts}`)
```
## Exercise Level 3
1. Create a human readable time format using the Date time object. The hour and the minute should be all the time two digits(7 hours should be 07 and 5 minutes should be 05 )
@ -494,4 +372,4 @@ console.log(`${day} / ${mount} / ${year} ${hour} : ${minut}`)
```
## [Home](../README.md) | [<< Day 2](./02_day_datatype.md) | [Day 4 >>](./04_day_conditional.md)
#### [Home](../README.md) | [<< Day 2](./02_day_datatype.md) | [Day 4 >>](./04_day_conditional.md)

@ -1,100 +1,16 @@
# Exercise Day 2 -Conditionals
# Day 4 - Conditional
### [Exercises: Level 1](#exercise-level-1)
## [Exercise:Solutions](#exercise-solutions)
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 another feedback stating to wait for the number of years he needs to turn 18.
```sh
Enter your age: 30
You are old enough to drive.
Enter your age:15
You are left with 3 years to drive.
```
1. Compare the values of myAge and yourAge using if … else. Based on the comparison and log the result to console stating who is older (me or you). Use prompt(“Enter your age:”) to get the age as input.
```sh
Enter your age: 30
You are 5 years older than me.
```
1. If a is greater than b return 'a is greater than b' else 'a is less than b'. Try to implement it in to ways
- using if else
- ternary operator.
```js
let a = 4
let b = 3
```
```sh
4 is greater than 3
```
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
Enter a number: 2
2 is an even number
Enter a number: 9
9 is is an odd number.
```
### [Exercises:Level 2](#exercise-level-2)
1. Write a code which can give grades 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
What is the day today? Saturday
Saturday is a weekend.
What is the day today? saturDaY
Saturday is a weekend.
What is the day today? Friday
Friday is a working day.
What is the day today? FrIDAy
Friday is a working day.
```
### [Exercises:Level 3](#exercise-level-3)
1. Write a program which tells the number of days in a month.
```sh
Enter a month: January
January has 31 days.
Enter a month: JANUARY
January has 31 day
Enter a month: February
February has 28 days.
Enter a month: FEbruary
February has 28 days.
```
1. Write a program which tells the number of days in a month, now consider leap year.
- ### [Exercise:Level 1](#exercise-level-1)
- ### [Exercise:Level 2](#exercise-level-2)
- ### [Exercise:Level 3](#exercise-level-3) <hr>
#### [Home](../README.md) | [<< Day 3](./03_day_operators.md) | [Day 5 >>](./05_day_arrays.md)
## Exercise Solutions
### Exercise Level 1
@ -183,7 +99,6 @@ else{
}
```
### Exercise Level 2
1. Write a code which can give grades to students according to theirs scores:
@ -336,6 +251,6 @@ switch(month){
}
```
#### [Home](../README.md) | [<< Day 3](./03_day_operators.md) | [Day 5 >>](./05_day_arrays.md)

@ -469,4 +469,4 @@ const countries = [
```
#### [Home](../README.md) | [<< Day 5](./05_day_arrays.md) | [Day 7 >>](./07_day_function.md)
#### [Home](../README.md) | [<< Day 4](./04_day_conditional.md) | [Day 6 >>](./06_day_loops.md)

@ -204,6 +204,40 @@ for(let i=1; i<=100; i+=2){
```
9. Use for loop to iterate from 0 to 100 and print only prime numbers
```js
//app.js
// Function to check if a number is prime
function isPrime(num) {
// 1 and numbers <= 1 are not prime
if (num <= 1) {
return false;
}
// 2 and 3 are prime
if (num <= 3) {
return true;
}
// Exclude even numbers and multiples of 3
if (num % 2 === 0 || num % 3 === 0) {
return false;
}
// Check divisibility from 5 upwards
for (let i = 5; i * i <= num; i += 6) {
if (num % i === 0 || num % (i + 2) === 0) {
return false;
}
}
return true;
}
// Loop from 0 to 100 and print prime numbers
for (let i = 0; i <= 100; i++) {
if (isPrime(i)) {
console.log(i);
}
}
```
10. Use for loop to iterate from 0 to 100 and print the sum of all numbers.
```
The sum of all numbers from 0 to 100 is 5050.

@ -948,3 +948,4 @@ function reverseCountries(countries) {
return copy.reverse();
}
```
#### [Home](../README.md) | [<< Day 6](./06_day_loops.md) | [Day 8 >>](./08_day_object.md)

@ -8,7 +8,7 @@
- ### [Exercise:Level 2](#exercises-level-2)
- ### [Exercise:Level 3](#exercises-level-3) <hr>
#### [Home](../README.md) | [<< Day 6](./06_day_loops.md) | [Day 8 >>](./08_day_object.md)
#### [Home](../README.md) | [<< Day 7](./07_day_function.md) | [Day 9 >>](./09_day_callbac_function.md)
## Exercise Solutions
@ -562,4 +562,7 @@ const products = [
}
likeProduct("hedfcg","hedfcg")
```
```
#### [Home](../README.md) | [<< Day 7](./07_day_function.md) | [Day 9 >>](./09_day_callbac_function.md)

@ -8,7 +8,7 @@
- ### [Exercise:Level 2](#exercises-level-2)
- ### [Exercise:Level 3](#exercises-level-3) <hr>
#### [Home](../README.md) | [<< Day 6](./06_day_loops.md) | [Day 8 >>](./08_day_object.md)
#### [Home](../README.md) | [<< Day 8](./08_day_object.md) | [Day 10 >>](./10_day_sets_and_maps.md)
## Exercise Solutions
@ -32,10 +32,10 @@ const products = [
1. Explain the difference between forEach, map, filter, and reduce.
```
foreach dizideki her bir eleman için bir fonksiyon çalıştırir.Dizideki elemani degistirebilir ama yeni bir dizi olisturamaz.
map foreach ile aynidir farki map yeni bir dizi döndürür.
reduce, bir dizideki her öğe için belirtilen bir fonksiyonu çalıştırır ve bu fonksiyonun sonuçlarını biriktirerek tek bir değer döndürür. Bu fonksiyon, dizinin her öğesini değiştiremez, ancak bir önceki fonksiyon çağrısının sonucunu alarak bir sonraki fonksiyon çağrısına aktarır.
filrer JavaScriptte filter metodu, bir dizideki elemanları belirli bir koşula göre filtrelemek için kullanılan bir dizidir. Filter metodu, orijinal diziyi değiştirmez, ancak koşulu sağlayan elemanlardan oluşan yeni bir dizi döndürür
foreach runs a function for each element in the array. It can change the element in the array, but it cannot create a new array.
map is the same as foreach, except map returns a new array.
reduce runs a specified function for each element in an array and accumulates the results of that function, returning a single value. This function cannot modify every element of the array, but takes the result of the previous function call and passes it to the next function call.
filterer In JavaScript, the filter method is an array used to filter elements in an array based on a certain condition. The filter method does not modify the original array, but returns a new array consisting of elements that satisfy the condition
```
2. Define a callback function before you use it in forEach, map, filter or reduce.
@ -509,4 +509,7 @@ console.log(result);
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)]
```
```
#### [Home](../README.md) | [<< Day 8](./08_day_object.md) | [Day 10 >>](./10_day_sets_and_maps.md)

@ -1,9 +1,32 @@
# Day 10 - Set And Maps
## [Exercise:Solutions](#exercise-solutions)
- ### [Exercise:Level 1](#exercises-level-1)
- ### [Exercise:Level 2](#exercises-level-2)
- ### [Exercise:Level 3](#exercises-level-3) <hr>
#### [Home](../README.md) | [<< Day 9](./09_day_callbac_function.md) | [Day 11 >>](./11_day_des_spreading.md)
## Exercise Solutions
### Exercises Level 1
1. create an empty set
```js
// app.js
const countries = new Set()
console.log(countries)
```
2. Create a set containing 0 to 10 using loop
```js
// app.js
const set = new Set()
set.add(0,)
@ -19,15 +42,23 @@ set.add(9)
set.add(10)
console.log(set)
```
3. Remove an element from a set
```js
// app.js
const set = new Set()
set.add(0,)
set.add(1)
set.add(2)
console.log(set.delete(1))
```
4. Clear a set
```js
// app.js
const set = new Set()
set.add(0,)
@ -35,14 +66,22 @@ set.add(1)
set.add(2)
set.clear()
console.log(set)
```
5. Create a set of 5 string elements from array
```js
// app.js
const arr = ['ayşe','fatma','dilan','cansu']
const set = new Set(arr)
console.log(set)
```
6. Create a map of countries and number of characters of a country
```js
// app.js
const map = new Map()
@ -50,8 +89,10 @@ map.set(1,'turkey')
map.set(2,'russıa')
map.set(3,'germaby')
console.log(map)
```
### Exercise Level 2
### Exercises Level 2
1. Find a union b
```js
@ -151,4 +192,7 @@ console.log(aUnionB)
{French:45},
{Arabic:25}
]
```
```
#### [Home](../README.md) | [<< Day 9](./09_day_callbac_function.md) | [Day 11 >>](./11_day_des_spreading.md)

@ -0,0 +1,175 @@
# Day 11 - Destruction And Spreading
## [Exercise:Solutions](#exercise-solutions)
- ### [Exercise:Level 1](#exercises-level-1)
- ### [Exercise:Level 2](#exercises-level-2)
- ### [Exercise:Level 3](#exercises-level-3) <hr>
#### [Home](../README.md) | [<< Day 10](./10_day_sets_and_maps.md) | [Day 12 >>](./12_day_regular_ex.md)
## Exercise Solutions
### Exercises Level 1
1. Destructure and assign the elements of constants array to e, pi, gravity, humanBodyTemp, waterBoilingTemp.
```js
//app.js
const constants = [2.72, 3.14, 9.81, 37.5, 100]
const [E,PI,G,humanBodyTemp,waterBoilingTemp] =constants
console.log(E,PI,G,humanBodyTemp,waterBoilingTemp)
```
2. Destructure and assign the elements of countries array to fin, est, sw, den, nor
```js
//app.js
const countries =['Finland','Estonia','Sweden','Denmark','Norway']
const [fin,est,swd,den,nor] = countries
console.log(fin,est,swd,den,nor)
```
3. Destructure the rectangle object by its properties or keys.
```js
//app.js
const rectangle ={
width:20,
height:10,
are:200,
perimeter:60
}
const {width,height,are,perimeter} = rectangle
console.log(width,height,are,perimeter)
```
### Exercises Level 2
1. Iterate through the users array and get all the keys of the object using destructuring
```js
//app.js
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
}
]
for( const {name,scores,skills,age} of users){
console.log(name,scores,skills,age)
}
```
2. Find the persons who have less than two skills
```js
//app.js
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
}
]
let a = users.forEach((element) => {
if(element.skills.length <=2){
console.log(element)
}
})
```
### Exercises Level 3
#### [Home](../README.md) | [<< Day 10](./10_day_sets_and_maps.md) | [Day 12 >>](./12_day_regular_ex.md)

@ -0,0 +1,94 @@
# Day 12 - Regex
## [Exercise:Solutions](#exercise-solutions)
- ### [Exercise:Level 1](#exercises-level-1)
- ### [Exercise:Level 2](#exercises-level-2)
- ### [Exercise:Level 3](#exercises-level-3) <hr>
#### [Home](../README.md) | [<< Day 11](./11_day_des_spreading.md) | [Day 13 >>](./13_day_consol_objmth.md)
## Exercise Solutions
### Exercises Level 1
1. Calculate the total annual income of the person from the following text. He earns 4000 euro from salary per month, 10000 euro annual bonus, 5500 euro online courses per month.
```js
// app.js
let text ="He earns 4000 euro from salary per month, 10000 euro annual bonus, 5500 euro online courses per month."
let pattern = /\d+/g
let numbers = text.match(pattern)
numbers = numbers.map(Number)
let montlySalary = numbers[0]
let bonus = numbers[1]
let montCourses = numbers[2]
console.log(`Annual income is ${(montlySalary*12) + (bonus) + (montCourses *12)}`)
```
2. The position of some particles on the horizontal x-axis -12, -4, -3 and -1 in the negative direction, 0 at origin, 4 and 8 in the positive direction. Extract these numbers and find the distance between the two furthest particles.
```js
// app.js
```
3. Write a pattern which identify if a string is a valid JavaScript variable
```js
// app.js
function isValidVariableName(str) {
// Birinci karakterin harf, alt çizgi veya dolar işareti olup olmadığını kontrol eden bir kalıp
var firstCharPattern = /^[a-zA-Z_$]/;
// Diğer karakterlerin harf, rakam, alt çizgi veya dolar işareti olup olmadığını kontrol eden bir kalıp
var otherCharPattern = /^[a-zA-Z0-9_$]*$/;
// Dizenin rezerve edilmiş bir kelime olup olmadığını kontrol eden bir dizi
var reservedWords = ["var", "let", "const", "function", "if", "else"];
// Dizenin boş olmadığını, birinci karakterin kalıpla eşleştiğini, diğer karakterlerin kalıpla eşleştiğini ve rezerve edilmiş kelimeler arasında olmadığını kontrol eder
return str && firstCharPattern.test(str) && otherCharPattern.test(str) && !reservedWords.includes(str);
}
console.log(isValidVariableName('21dzfgdf'))
```
### Exercises Level 2
1. Write a function called tenMostFrequentWords which get the ten most frequent word from a string?
```
let paragraph = `I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love.`
```
```js
// app.js
function tenMostFrequentWords(paragraph) {
// Paragrafı kelimelere ayırırken noktalama işaretlerini ve büyük harfleri yok sayar
var words = paragraph.toLowerCase().replace(/[.,]/g, '').split(/\s/);
// Her kelimenin frekansını tutan bir nesne oluşturur
var freqMap = {};
words.forEach(function(word) {
// Kelime nesnede yoksa 0, varsa mevcut değerine 1 ekler
freqMap[word] = (freqMap[word] || 0) + 1;
});
// Nesneyi bir diziye dönüştürür ve frekansa göre azalan şekilde sıralar
var sorted = Object.entries(freqMap).sort(function(a, b) {
return b[1] - a[1];
});
// Sadece ilk 10 elemanı alır ve kelimeleri bir dizi olarak döndürür
return sorted.slice(0, 10).map(function(pair) {
return pair[0];
});
}
console.log( tenMostFrequentWords(paragraph))
```
### Exercises Level 3
1. Writ a function which cleans text. Clean the following text. After cleaning, count three most frequent words in the string.
#### [Home](../README.md) | [<< Day 11](./11_day_des_spreading.md) | [Day 13 >>](./13_day_consol_objmth.md)

@ -0,0 +1,113 @@
# Day 13 - Console Object Methods
## [Exercise:Solutions](#exercise-solutions)
- ### [Exercise:Level 1](#exercises-level-1)
- ### [Exercise:Level 2](#exercises-level-2)
- ### [Exercise:Level 3](#exercises-level-3) <hr>
#### [Home](../README.md) | [<< Day 12](./12_day_regular_ex.md) | [Day 14 >>](./14_day_error_handling.md)
## Exercise Solutions
### Exercises Level 1
1. Display the countries array as a table
```js
// app.js
const countries = ['Norway', 'Sweden','England','Iceland']
console.table(countries)
```
2. Display the countries object as a table
```js
// app.js
const countries ={
countri: 'Germany',
popolation: 564654,
lamgue: 'German'
}
console.table(countries)
```
3. Use console.group() to group logs
```js
// app.js
const names = ['Asabeneh', 'Brook', 'David', 'John']
const countries = [
['Finland', 'Helsinki'],
['Sweden', 'Stockholm'],
['Norway', 'Oslo']
]
const user = {
name: 'Asabeneh',
title: 'Programmer',
country: 'Finland',
city: 'Helsinki',
age: 250
}
const users = [
{
name: 'Asabeneh',
title: 'Programmer',
country: 'Finland',
city: 'Helsinki',
age: 250
},
{
name: 'Eyob',
title: 'Teacher',
country: 'Sweden',
city: 'London',
age: 25
},
{
name: 'Asab',
title: 'Instructor',
country: 'Norway',
city: 'Oslo',
age: 22
},
{
name: 'Matias',
title: 'Developer',
country: 'Denmark',
city: 'Copenhagen',
age: 28
}
]
console.group('names')
console.log(names)
console.groupEnd()
console.group('countries')
console.log(countries)
console.groupEnd()
console.group('user')
console.log(user)
console.groupEnd()
```
### Exercises Level 2
1. 10 > 2 * 10 use console.assert()
2. Write a warning message using console.warn()
3. Write an error message using console.error()
### Exercises Level 3
1. Check the speed difference among the following loops: while, for, for of, forEach
#### [Home](../README.md) | [<< Day 12](./12_day_regular_ex.md) | [Day 14 >>](./14_day_error_handling.md)

@ -0,0 +1,8 @@
# Day 14 - Error Handling
### No exercise today. Continue from day 15
#### [Home](../README.md) | [<< Day 13](./13_day_consol_objmth.md) | [Day 15>>](./15_day_classes.md)

@ -0,0 +1,242 @@
# Day 15 - Classes
## [Exercise:Solutions](#exercise-solutions)
- ### [Exercise:Level 1](#exercises-level-1)
- ### [Exercise:Level 2](#exercises-level-2)
- ### [Exercise:Level 3](#exercises-level-3) <hr>
#### [Home](../README.md) | [<< Day 14](./14_day_error_handling.md) | [Day 16 >>](./16_day_JSON.md)
## Exercise Solutions
### Exercises Level 1
1. Create an Animal class. The class will have name, age, color, legs properties and create different methods
```js
// app.js
class Animal {
constructor(name,age,color,leg){
this.name = name
this.age=age
this.color=color
this.leg=leg
}
calculaterBirthYear(){
const currentYear = new Date().getFullYear()
const birthYear = currentYear - this.age
return birthYear
}
}
```
2. Create a Dog and Cat child class from the Animal Class.
```js
// app.js
class Animal {
constructor(name,age,color,leg){
this.name = name
this.age=age
this.color=color
this.leg=leg
}
calculaterBirthYear(){
const currentYear = new Date().getFullYear()
const birthYear = currentYear - this.age
return birthYear
}
}
const dog1 = new Animal("beşo",5,"red",4)
const cat1= new Animal("lesi",3,"white",2)
console.log(dog1.calculaterBirthYear())
console.log(cat1.calculaterBirthYear())
```
### Exercises Level 2
1. Override the method you create in Animal class
```js
// app.js
class Animal {
constructor(name,age,color,leg){
this.name = name
this.age=age
this.color=color
this.leg=leg
}
static calculaterBirthYear(){
const currentYear = new Date().getFullYear()
const birthYear = currentYear - this.age
return birthYear
}
}
const dog1 = new Animal("beşo",5,"red",4)
const cat1= new Animal("lesi",3,"white",2)
console.log(dog1.calculaterBirthYear())
console.log(cat1.calculaterBirthYear())
```
### Exercises Level 3
1. Let's 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 a class called Statistics and create all the functions which do statistical calculations as method for the Statistics class. Check the output below.
```js
// app.js
class Statistics {
constructor(data) {
this.data = data;
}
mean() {
return this.data.reduce((a, b) => a + b) / this.data.length;
}
median() {
const sortedData = this.data.sort((a, b) => a - b);
const middleIndex = Math.floor(sortedData.length / 2);
if (sortedData.length % 2 === 0) {
return (sortedData[middleIndex - 1] + sortedData[middleIndex]) / 2;
} else {
return sortedData[middleIndex];
}
}
mode() {
const frequencyTable = {};
let maxFrequency = 0;
let modes = [];
for (const value of this.data) {
frequencyTable[value] = (frequencyTable[value] || 0) + 1;
if (frequencyTable[value] > maxFrequency) {
maxFrequency = frequencyTable[value];
modes = [value];
} else if (frequencyTable[value] === maxFrequency) {
modes.push(value);
}
}
return modes;
}
range() {
return Math.max(...this.data) - Math.min(...this.data);
}
variance() {
const mean = this.mean();
return this.data.reduce((a, b) => a + (b - mean) ** 2, 0) / this.data.length;
}
standardDeviation() {
return Math.sqrt(this.variance());
}
minimum() {
return Math.min(...this.data);
}
maximum() {
return Math.max(...this.data);
}
count() {
return this.data.length;
}
percentile(p) {
const sortedData = this.data.sort((a, b) => a - b);
const index = (p / 100) * (sortedData.length - 1);
if (Number.isInteger(index)) {
return sortedData[index];
} else {
const lowerIndex = Math.floor(index);
const upperIndex = Math.ceil(index);
return (sortedData[lowerIndex] + sortedData[upperIndex]) / 2;
}
}
frequencyDistribution() {
const frequencyTable = {};
for (const value of this.data) {
frequencyTable[value] = (frequencyTable[value] || 0) + 1;
}
return frequencyTable;
}
}
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]
const stats = new Statistics(ages);
console.log(`Mean: ${stats.mean()}`);
console.log(`Median: ${stats.median()}`);
console.log(`Mode: ${stats.mode()}`);
console.log(`Range: ${stats.range()}`);
console.log(`Variance: ${stats.variance()}`);
console.log(`Standard Deviation: ${stats.standardDeviation()}`);
console.log(`Minimum: ${stats.minimum()}`);
console.log(`Maximum: ${stats.maximum()}`);
console.log(`Count: ${stats.count()}`);
console.log(`25th Percentile: ${stats.percentile(25)}`);
console.log(`Frequency Distribution: ${JSON.stringify(stats.frequencyDistribution())}`);
```
1. Create a class 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 also a set of expenses and its description.
```js
// ap.js
class PersonAccount {
constructor(name, surname, incomes, expenses) {
this.name = name;
this.surname = surname;
this.incomes = incomes;
this.expenses = expenses;
}
totalIncome() {
return this.incomes.reduce((a, b) => a + b, 0);
}
totalExpense() {
return this.expenses.reduce((a, b) => a + b, 0);
}
accountInfo() {
return `${this.name} ${this.surname} has a total income of ${this.totalIncome()} and a total expense of ${this.totalExpense()}.`;
}
addIncome(income) {
this.incomes.push(income);
}
addExpense(expense) {
this.expenses.push(expense);
}
accountBalance() {
return this.totalIncome() - this.totalExpense();
}
}
const person = new PersonAccount('Nevzat', 'Atalay', [1000, 2000, 3000], [500, 1000]);
console.log(person.accountInfo()); // John Doe has a total income of 6000 and a total expense of 1500.
console.log(person.accountBalance()); // 4500
```
#### [Home](../README.md) | [<< Day 14](./14_day_error_handling.md) | [Day 16 >>](./16_day_JSON.md)

@ -0,0 +1,304 @@
# Day 16 - Json
## [Exercise:Solutions](#exercise-solutions)
- ### [Exercise:Level 1](#exercises-level-1)
- ### [Exercise:Level 2](#exercises-level-2)
- ### [Exercise:Level 3](#exercises-level-3) <hr>
#### [Home](../README.md) | [<< Day 15](./15_day_classes.md) | [Day 17 >>](./17_day_wep%20storege.md)
## Exercise Solutions
```js
const skills = ['HTML', 'CSS', 'JS', 'React','Node', 'Python']
let age = 250;
let isMarried = true
const student = {
firstName:'Asabeneh',
lastName:'Yetayehe',
age:250,
isMarried:true,
skills:['HTML', 'CSS', 'JS', 'React','Node', 'Python', ]
}
const txt = `{
"Alex": {
"email": "alex@alex.com",
"skills": [
"HTML",
"CSS",
"JavaScript"
],
"age": 20,
"isLoggedIn": false,
"points": 30
},
"Asab": {
"email": "asab@asab.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"Redux",
"MongoDB",
"Express",
"React",
"Node"
],
"age": 25,
"isLoggedIn": false,
"points": 50
},
"Brook": {
"email": "daniel@daniel.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"React",
"Redux"
],
"age": 30,
"isLoggedIn": true,
"points": 50
},
"Daniel": {
"email": "daniel@alex.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"Python"
],
"age": 20,
"isLoggedIn": false,
"points": 40
},
"John": {
"email": "john@john.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"React",
"Redux",
"Node.js"
],
"age": 20,
"isLoggedIn": true,
"points": 50
},
"Thomas": {
"email": "thomas@thomas.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"React"
],
"age": 20,
"isLoggedIn": false,
"points": 40
},
"Paul": {
"email": "paul@paul.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"MongoDB",
"Express",
"React",
"Node"
],
"age": 20,
"isLoggedIn": false,
"points": 40
}
}
```
### Exercises Level 1
1. Change skills array to JSON using JSON.stringify()
```js
//app.js
const skills = ['HTML', 'CSS', 'JS', 'React','Node', 'Python']
console.log(JSON.stringify(skills))
```
1. Stringify the age variable
```js
//app.js
let age = 250;
console.log(JSON.stringify(age))
```
1. Stringify the isMarried variable
```js
//app.js
let isMarried = true
console.log(JSON.stringify(isMarried))
```
1. Stringify the student object
```js
//app.js
const student = {
firstName:'Asabeneh',
lastName:'Yetayehe',
age:250,
isMarried:true,
skills:['HTML', 'CSS', 'JS', 'React','Node', 'Python', ]
}
console.log(JSON.stringify(student))
```
### Exercises Level 2
1. Stringify the students object with only firstName, lastName and skills properties
```js
//app.js
const student = {
firstName:'Asabeneh',
lastName:'Yetayehe',
age:250,
isMarried:true,
skills:['HTML', 'CSS', 'JS', 'React','Node', 'Python', ]
};
const studentString = JSON.stringify({
firstName: student.firstName,
lastName: student.lastName,
skills: student.skills
});
console.log(studentString);
```
### Exercises Level 3
1. Parse the *txt* JSON to object.
```js
//app.js
const obj = JSON.parse(txt);
console.log(obj);
```
2. Find the user who has many skills from the variable stored in *txt*.
```js
//app.js
const txt = {
"Alex": {
"email": "alex@alex.com",
"skills": [
"HTML",
"CSS",
"JavaScript"
],
"age": 20,
"isLoggedIn": false,
"points": 30
},
"Asab": {
"email": "asab@asab.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"Redux",
"MongoDB",
"Express",
"React",
"Node"
],
"age": 25,
"isLoggedIn": false,
"points": 50
},
"Brook": {
"email": "daniel@daniel.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"React",
"Redux"
],
"age": 30,
"isLoggedIn": true,
"points": 50
},
"Daniel": {
"email": "daniel@alex.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"Python"
],
"age": 20,
"isLoggedIn": false,
"points": 40
},
"John": {
"email": "john@john.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"React",
"Redux",
"Node.js"
],
"age": 20,
"isLoggedIn": true,
"points": 50
},
"Thomas": {
"email": "thomas@thomas.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"React"
],
"age": 20,
"isLoggedIn": false,
"points": 40
},
"Paul": {
"email": "paul@paul.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"MongoDB",
"Express",
"React",
"Node"
],
"age": 20,
"isLoggedIn": false,
"points": 40
}
};
const userWithMostSkills = Object.keys(txt).reduce((a, b) => txt[a].skills.length > txt[b].skills.length ? a : b);
console.log(`The user with the most skills is ${userWithMostSkills}.`);
```
#### [Home](../README.md) | [<< Day 15](./15_day_classes.md) | [Day 17 >>](./17_day_wep%20storege.md)

@ -0,0 +1,96 @@
# Day 17 - Web Storaage
## [Exercise:Solutions](#exercise-solutions)
- ### [Exercise:Level 1](#exercises-level-1)
- ### [Exercise:Level 2](#exercises-level-2)
- ### [Exercise:Level 3](#exercises-level-3) <hr>
#### [Home](../README.md) | [<< Day 16](./16_day_JSON.md) | [Day 18 >>](./18_day_promise.md)
## Exercise Solutions
### Exercises: Level 1
1. Store you first name, last name, age, country, city in your browser localStorage.
```js
// app.js
let firstName = "nevzat"
let lasrName="Atalay"
let age= 25
let city ="BİTLİS"
let country = "Turkey"
localStorage.setItem("name",JSON.stringify(firstName))
localStorage.setItem("lastName",JSON.stringify(lasrName))
localStorage.setItem("age",JSON.stringify(age))
localStorage.setItem("city",JSON.stringify(city))
localStorage.setItem("country",JSON.stringify(country))
```
### Exercises: Level 2
1. Create a student object. The student object will have first name, last name, age, skills, country, enrolled keys and values for the keys. Store the student object in your browser localStorage.
```js
// app.js
let student = {
firstName:"Nevzat",
lastName:"Atalay",
age:25,
skills:["HTML","CSS","JavaScript"],
country:"Turkey",
}
localStorage.setItem("student",JSON.stringify(student))
```
### Exercises: Level 3
1. Create an object 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 also a set of expenses and its description.
```js
// ap.js
class PersonAccount {
constructor(name, surname, incomes, expenses) {
this.name = name;
this.surname = surname;
this.incomes = incomes;
this.expenses = expenses;
}
totalIncome() {
return this.incomes.reduce((a, b) => a + b, 0);
}
totalExpense() {
return this.expenses.reduce((a, b) => a + b, 0);
}
accountInfo() {
return `${this.name} ${this.surname} has a total income of ${this.totalIncome()} and a total expense of ${this.totalExpense()}.`;
}
addIncome(income) {
this.incomes.push(income);
}
addExpense(expense) {
this.expenses.push(expense);
}
accountBalance() {
return this.totalIncome() - this.totalExpense();
}
}
const person = new PersonAccount('Nevzat', 'Atalay', [1000, 2000, 3000], [500, 1000]);
console.log(person.accountInfo());
console.log(person.accountBalance()); // 4500
```
#### [Home](../README.md) | [<< Day 16](./16_day_JSON.md) | [Day 18 >>](./18_day_promise.md)

@ -0,0 +1,101 @@
# Day 18 - Promise
## [Exercise:Solutions](#exercise-solutions)
- ### [Exercise:Level 1](#exercises-level-1)
- ### [Exercise:Level 2](#exercises-level-2)
- ### [Exercise:Level 3](#exercises-level-3) <hr>
#### [Home](../README.md) | [<< Day 17](./17_day_wep%20storege.md) | [Day 19 >>](./19_day_clouse.md)
## Exercise Solutions
### Exercises: Level 1
1. Read the countries API using fetch and print the name of country, capital, languages, population and area.
```js
// app.js
const countriesAPI = 'https://restcountries.com/v2/all'
fetch('https://restcountries.com/v2/all')
.then(response => response.json())
.then(data => {
data.forEach(country => {
const name = country.name;
const capital = country.capital;
const languages = country.languages.map(language => language.name);
const population = country.population;
const region = country.region;
console.log(`${name}, başkenti ${capital}'dir. Nüfusu ${population} ve bölgesi ${region}. Konuşulan diller: ${languages.join(', ')}`);
});
});
```
### Exercises: Level 2
1. Print out all the cat names in to catNames variable.
```js
// app.js
fetch('https://api.thecatapi.com/v1/breeds')
.then(response => response.json())
.then(data => {
const catNames = data.map(cat => cat.name);
console.log(catNames);
});
```
### Exercises: Level 3
1. Read the cats api and find the average weight of cat in metric unit.
```js
// app.js
const catsAPI = 'https://api.thecatapi.com/v1/breeds'
fetch('https://api.thecatapi.com/v1/breeds')
.then(response => response.json())
.then(data => {
const weights = data.map(cat => cat.weight.metric);
console.log(weights);
});
```
2. Read the countries api and find out the 10 largest countries
```js
// app.js
fetch('https://restcountries.com/v2/all')
.then(response => response.json())
.then(data => {
data.sort((a, b) => b.area - a.area);
const top10 = data.slice(0, 10);
top10.forEach(country => {
const name = country.name;
const capital = country.capital;
const languages = country.languages.map(language => language.name);
const population = country.population;
const region = country.region;
console.log(`${name}, başkenti ${capital}'dir. Nüfusu ${population} ve bölgesi ${region}. Konuşulan diller: ${languages.join(', ')}`);
});
});
```
3. Read the countries api and count total number of languages in the world used as officials.
```js
// app.js
fetch('https://restcountries.com/v2/all')
.then(response => response.json())
.then(data => {
const languages = new Set();
data.forEach(country => {
country.languages.forEach(language => {
languages.add(language.name);
});
});
console.log(`Dünya genelinde resmi olarak kullanılan dillerin toplam sayısı: ${languages.size}`);
});
```
#### [Home](../README.md) | [<< Day 17](./17_day_wep%20storege.md) | [Day 19 >>](./19_day_clouse.md)

@ -0,0 +1,74 @@
# Day 19 - Closures
## [Exercise:Solutions](#exercise-solutions)
- ### [Exercise:Level 1](#exercises-level-1)
- ### [Exercise:Level 2](#exercises-level-2)
- ### [Exercise:Level 3](#exercises-level-3) <hr>
#### [Home](../README.md) | [<< Day 18](./18_day_promise.md) | [Day 20 >>](./20_day_cleanCode.md)
## Exercise Solutions
### Exercises: Level 1
1. Create a closure which has one inner function
```js
// app.js
function myFunction(){
let firstName ="Nevzat"
let lastName = "Atalay"
function innerFunction(){
return console.log(firstName,lastName)
}
return innerFunction
}
const innerFun = myFunction()
innerFun()
```
### Exercises: Level 2
1. Create a closure which has three inner functions
```js
// app.js
function myFunction(){
let a =5
let b = 7
function total(){
return a + b
}
function extraction(){
return a - b
}
function multiply(){
return a * b
}
return{
total:total(),
extraction:extraction(),
multiply:multiply()
}
}
const innerFun = myFunction()
console.log(innerFun.total)
console.log(innerFun.extraction)
console.log(innerFun.multiply)
```
### Exercises: Level 3
1. Create a personAccount out function. It has firstname, lastname, incomes, expenses inner variables. It has totalIncome, totalExpense, accountInfo,addIncome, addExpense and accountBalance inner functions. Incomes is a set of incomes and its description and expenses is also a set of expenses and its description.
#### [Home](../README.md) | [<< Day 18](./18_day_promise.md) | [Day 20 >>](./20_day_cleanCode.md)

@ -0,0 +1,7 @@
# Day 20 Clean Code
### No exercise today. Continue from day 21
#### [Home](../README.md) | [<< Day 19](./19_day_clouse.md) | [Day 21>>](./21_day_DOM.md)

@ -0,0 +1,162 @@
# Day 21 - Dom 1
## [Exercise:Solutions](#exercise-solutions)
- ### [Exercise:Level 1](#exercises-level-1)
- ### [Exercise:Level 2](#exercises-level-2)
- ### [Exercise:Level 3](#exercises-level-3) <hr>
#### [Home](../README.md) | [<< Day 20](./20_day_cleanCode.md) | [Day 22 >>](./22_day_DOM2.md)
## Exercise Solutions
### Exercise Level 1
1. Create an index.html file and put four p elements as above: Get the first paragraph by using document.querySelector(tagname) and tag name
````js
<p class="paragraph" id="first-paragraph">first</p>
<p class="paragraph" id="second-paragraph">second</p>
<p class="paragraph" id="third-paragraph">third</p>
<p class="paragraph"></p>```
```js
//app.js
const firstParagraph = document.querySelector('p')
console.log(firstParagraph)
````
2. Get each of the the paragraph using document.querySelector('#id') and by their id
```js
//app.js
let firstParagraph = document.querySelector("#first-paragraph");
let secondParagraph = document.querySelector("#second-paragraph");
let thirdParagraph = document.querySelector("#third-paragraph");
console.log(firstParagraph, secondParagraph, thirdParagraph);
```
3. Get all the p as nodeList using document.querySelectorAll(tagname) and by their tag name
```js
//app.js
const allParagraph = document.querySelectorAll("p");
console.log(allParagraph);
```
4. Lop through the nodeList and get the text content of each paragraph
```js
//app.js
const allParagraph = document.querySelectorAll("p");
for (let i = 0; i < allParagraph.length; i++) {
console.log(allParagraph[i]);
}
```
5. Set a text content to paragraph the fourth paragraph,Fourth Paragraph
```js
//app.js
const paragraf = document.querySelectorAll("p");
paragraf[3].textContent = "four paragraf";
```
6. Set id and class attribute for all the paragraphs using different attribute setting methods
```js
//app.js
const paragraph = document.querySelectorAll("p");
paragraph[0].className = "parag_one";
paragraph[0].id = "id_one";
paragraph[1].setAttribute("class", "paragraph_two");
paragraph[1].setAttribute("id", "id_two");
paragraph[2].classList = "paragraph_thre";
paragraph[2].id = "id_thre";
paragraph[3].setAttribute("class", "paragraph_four");
paragraph[3].setAttribute("id", "id_four");
console.log(paragraph);
```
### Exercise Level 2
1. Change stye of each paragraph using JavaScript(eg. color, background, border, font-size, font-family)
const paragraf =document.querySelectorAll('p')
paragraf[0].style.background='blue'
paragraf[1].style.fontSize='50px'
paragraf[2].style.border='1px solid red'
paragraf[3].style.color='yellow'
2. Select all paragraphs and loop through each elements and give the first and third paragraph a color of green, and the second and the fourth paragraph a red color
const paragraf =document.querySelectorAll('p')
paragraf.forEach((paragraf,i) => {
if(i % 2 ===0){
paragraf.style.backgroundColor='green'
}
else(paragraf.style.backgroundColor='red')
})
Set text content, id and class to each paragraph
3.
const paragraf =document.querySelectorAll('p')
for(const par of paragraf){
par.className='class'
par.id='id'
par.textContent='This is a paragraph '
}
### Exercise Level 3
#### DOM: Mini project 1
1. Develop the following application, use the following HTML elements to get started with. You will get the same code on starter folder. Apply all the styles and functionality using JavaScript only.
- The year color is changing every 1 second
- The date and time background color is changing every on seconds
- Completed challenge has background green
- Ongoing challenge has background yellow
- Coming challenges have background red
```html
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript for Everyone:DOM</title>
</head>
<body>
<div class="wrapper">
<h1>Asabeneh Yetayeh challenges in 2020</h1>
<h2>30DaysOfJavaScript Challenge</h2>
<ul>
<li>30DaysOfPython Challenge Done</li>
<li>30DaysOfJavaScript Challenge Ongoing</li>
<li>30DaysOfReact Challenge Coming</li>
<li>30DaysOfFullStack Challenge Coming</li>
<li>30DaysOfDataAnalysis Challenge Coming</li>
<li>30DaysOfReactNative Challenge Coming</li>
<li>30DaysOfMachineLearning Challenge Coming</li>
</ul>
</div>
</body>
</html>
```
#### [Home](../README.md) | [<< Day 20](./20_day_cleanCode.md) | [Day 22 >>](./22_day_DOM2.md)

@ -0,0 +1,162 @@
# Day 22 - Dom 2
## [Exercise:Solutions](#exercise-solutions)
- ### [Exercise:Level 1](#exercises-level-1)
- ### [Exercise:Level 2](#exercises-level-2)
- ### [Exercise:Level 3](#exercises-level-3) <hr>
#### [Home](../README.md) | [<< Day 21](./21_day_DOM.md) | [Day 23 >>](./23_day_event.md)
## Exercise Solutions
### Exercise Level 1
1. Create a div container on HTML document and create 100 to 100 numbers dynamically and append to the container div.
- Even numbers background is green
- Odd numbers background is yellow
- Prime numbers background is red
```js
// app.js
// Bir asal sayı olup olmadığını kontrol eden bir fonksiyon tanımlayın
function isPrime(n) {
// 0 ve 1 asal sayı değildir
if (n === 0 || n === 1) {
return false;
}
// 2 asal sayının tek çiftidir
if (n === 2) {
return true;
}
// Çift sayılar asal sayı olamaz
if (n % 2 === 0) {
return false;
}
// 3'ten n'in kareköküne kadar olan tek sayılara bölünebilir mi diye bakın
let sqrt = Math.sqrt(n);
for (let i = 3; i <= sqrt; i += 2) {
if (n % i === 0) {
return false;
}
}
// Hiçbir sayıya bölünemiyorsa, asal sayıdır
return true;
}
// HTML'de bir tablo elemanı seçin
let table = document.getElementById("table");
// Tabloyu sıfırlayın
table.innerHTML = "";
// Satır ve sütun sayısını belirleyin
let rows = 17;
let cols = 6;
// Her satır için bir döngü başlatın
for (let i = 0; i < rows; i++) {
// Bir tablo satırı oluşturun
let tr = document.createElement("tr");
// Her sütun için bir döngü başlatın
for (let j = 0; j < cols; j++) {
// Bir tablo hücresi oluşturun
let td = document.createElement("td");
// Hücredeki sayıyı hesaplayın
let num = i * cols + j;
// Hücreye sayıyı yazın
td.textContent = num;
// Sayının rengini belirleyin
let color;
if (isPrime(num)) {
// Asal sayılar kırmızıdır
color = "red";
} else if (num % 2 === 0) {
// Çift sayılar yeşildir
color = "green";
} else {
// Tek sayılar sarıdır
color = "yellow";
}
// Hücrenin arka plan rengini ayarlayın
td.style.backgroundColor = color;
// Hücreyi satıra ekleyin
tr.appendChild(td);
}
// Satırı tabloya ekleyin
table.appendChild(tr);
}
```
### Exercised Level 2
1. Use the countries array to display all the countries.See the design
```js
// app.js
// Create an array of country names
let countries = ["Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antigua and Barbuda", "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon"];
// Select a div element in HTML
let div = document.getElementById("div");
// Clear the div content
div.innerHTML = "";
// Set the number of rows and columns
let rows = '6';
let cols = '6';
// Loop through each row
for (let i = 0; i < rows; i++) {
// Create a paragraph element
let p = document.createElement("p");
// Loop through each column
for (let j = 0; j < cols; j++) {
// Get the index of the country in the array
let index = i * cols + j;
// Check if the index is valid
if (index < countries.length) {
// Get the country name
let country = countries[index];
// Create a span element
let span = document.createElement("span");
// Set the span content to the country name
span.textContent = country;
// Set the span style to have a border and some padding
span.style.border = "1px solid black";
span.style.padding = "5px";
// Append the span to the paragraph
p.appendChild(span);
}
}
// Append the paragraph to the div
div.appendChild(p);
}
```
### Exercie Level 3
#### [Home](../README.md) | [<< Day 21](./21_day_DOM.md) | [Day 23 >>](./23_day_event.md)

@ -0,0 +1,109 @@
# Day 23 - Event Listener
## [Exercise:Solutions](#exercise-solutions)
- ### [Exercise:Level 1](#exercises-level-1)
#### [Home](../README.md) | [<< Day 22](./22_day_DOM2.md) | [Day 24 >>](../days/day_24/day_24.md)
## Exercise Solutions
### Exercise Level 1
1. Generating numbers and marking evens, odds and prime numbers with three different colors. See the image below.
```html
// index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sayıları Göster</title>
<style>
*{
margin: 0;
padding: 0;
text-align: center;
}
#result {
border:1px solid;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
margin-top: 20px;
}
li{
border:1px solid;
list-style: none;
text-align: center;
display: inline-block;
}
h5{
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="container"><h1>Number Generator</h1>
<h3>30DaysOfJavaScript:DOM Day 3</h3>
<h5>Nevzat Atalay</h5>
<input type="number" id="inputNumber" placeholder="Bir sayı girin">
<button onclick="displayNumbers()">Göster</button>
<div id="result"></div></div>
<script>
function isPrime(num) {
if (num < 2) {
return false;
}
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
function displayNumbers() {
const inputNumber = document.getElementById('inputNumber').value;
const resultDiv = document.getElementById('result');
resultDiv.innerHTML = ''; // Temizleme
try {
const num = parseInt(inputNumber);
if (isNaN(num) || num < 0) {
alert("Geçerli bir pozitif sayı giriniz.");
return;
}
for (let i = 1; i <= num; i++) {
let color = i % 2 === 1 ? 'yellow' : 'green';
if (isPrime(i)) {
color = 'red';
}
resultDiv.innerHTML += `<li style="background-Color:${color}">${i}</li>`;
}
} catch (error) {
alert("Bir hata oluştu. Lütfen geçerli bir sayı giriniz.");
}
}
</script>
</body>
</html>
```
2. Generating the keyboard code code using even listener. The image below.
```js
//app.js
const div =document.getElementById("div")
window.addEventListener("keydown", (e)=>{
const li = document.createElement("li")
div.innerHTML=""
li.innerHTML= `Your pressed ${e.code}`
div.appendChild(li)
})
```
#### [Home](../README.md) | [<< Day 22](./22_day_DOM2.md) | [Day 24 >>](../days/day_24/day_24.md)

@ -0,0 +1,195 @@
const countriess = [
'Afghanistan',
'Albania',
'Algeria',
'Andorra',
'Angola',
'Antigua and Barbuda',
'Argentina',
'Armenia',
'Australia',
'Austria',
'Azerbaijan',
'Bahamas',
'Bahrain',
'Bangladesh',
'Barbados',
'Belarus',
'Belgium',
'Belize',
'Benin',
'Bhutan',
'Bolivia',
'Bosnia and Herzegovina',
'Botswana',
'Brazil',
'Brunei',
'Bulgaria',
'Burkina Faso',
'Burundi',
'Cambodia',
'Cameroon',
'Canada',
'Cape Verde',
'Central African Republic',
'Chad',
'Chile',
'China',
'Colombi',
'Comoros',
'Congo (Brazzaville)',
'Congo',
'Costa Rica',
"Cote d'Ivoire",
'Croatia',
'Cuba',
'Cyprus',
'Czech Republic',
'Denmark',
'Djibouti',
'Dominica',
'Dominican Republic',
'East Timor (Timor Timur)',
'Ecuador',
'Egypt',
'El Salvador',
'Equatorial Guinea',
'Eritrea',
'Estonia',
'Ethiopia',
'Fiji',
'Finland',
'France',
'Gabon',
'Gambia, The',
'Georgia',
'Germany',
'Ghana',
'Greece',
'Grenada',
'Guatemala',
'Guinea',
'Guinea-Bissau',
'Guyana',
'Haiti',
'Honduras',
'Hungary',
'Iceland',
'India',
'Indonesia',
'Iran',
'Iraq',
'Ireland',
'Israel',
'Italy',
'Jamaica',
'Japan',
'Jordan',
'Kazakhstan',
'Kenya',
'Kiribati',
'Korea, North',
'Korea, South',
'Kuwait',
'Kyrgyzstan',
'Laos',
'Latvia',
'Lebanon',
'Lesotho',
'Liberia',
'Libya',
'Liechtenstein',
'Lithuania',
'Luxembourg',
'Macedonia',
'Madagascar',
'Malawi',
'Malaysia',
'Maldives',
'Mali',
'Malta',
'Marshall Islands',
'Mauritania',
'Mauritius',
'Mexico',
'Micronesia',
'Moldova',
'Monaco',
'Mongolia',
'Morocco',
'Mozambique',
'Myanmar',
'Namibia',
'Nauru',
'Nepal',
'Netherlands',
'New Zealand',
'Nicaragua',
'Niger',
'Nigeria',
'Norway',
'Oman',
'Pakistan',
'Palau',
'Panama',
'Papua New Guinea',
'Paraguay',
'Peru',
'Philippines',
'Poland',
'Portugal',
'Qatar',
'Romania',
'Russia',
'Rwanda',
'Saint Kitts and Nevis',
'Saint Lucia',
'Saint Vincent',
'Samoa',
'San Marino',
'Sao Tome and Principe',
'Saudi Arabia',
'Senegal',
'Serbia and Montenegro',
'Seychelles',
'Sierra Leone',
'Singapore',
'Slovakia',
'Slovenia',
'Solomon Islands',
'Somalia',
'South Africa',
'Spain',
'Sri Lanka',
'Sudan',
'Suriname',
'Swaziland',
'Sweden',
'Switzerland',
'Syria',
'Taiwan',
'Tajikistan',
'Tanzania',
'Thailand',
'Togo',
'Tonga',
'Trinidad and Tobago',
'Tunisia',
'Turkey',
'Turkmenistan',
'Tuvalu',
'Uganda',
'Ukraine',
'United Arab Emirates',
'United Kingdom',
'United States',
'Uruguay',
'Uzbekistan',
'Vanuatu',
'Vatican City',
'Venezuela',
'Vietnam',
'Yemen',
'Zambia',
'Zimbabwe'
]

File diff suppressed because it is too large Load Diff

@ -0,0 +1,98 @@
// select element
const button = document.querySelector("#button")
const div = document.getElementById("wrapper")
div.style.display = "none"
// event listener
eventListener()
function eventListener() {
button.addEventListener("click", showWrapper)
}
// calculate weight on planets
function calculateWeight() {
const inputValue = document.querySelector("#input-value")
const planet = document.querySelector("#planetName")
if(!typeof inputValue === Number || inputValue.value == "" ){
alert("geçersiz deger")
}
else{
const img = document.createElement("img")
div.appendChild(img)
let gravity;
let planetName;
switch (planet.value) {
case "mercury":
gravity = 3.7;
planetName = "Merkür";
img.src = "./images/mercury.png"
break;
case "venus":
gravity = 8.87;
planetName = "Venüs";
img.src = "./images/venus.png"
break;
case "earth":
gravity = 9.81;
planetName = "Dünya";
img.src = "./images/earth.png"
break;
case "mars":
gravity = 3.711;
planetName = "Mars";
img.src = "./images/mars.png"
break;
case "jupiter":
gravity = 24.79;
planetName = "Jüpiter";
img.src = "./images/jupiter.png"
break;
case "saturn":
gravity = 10.44;
planetName = "Satürn";
img.src = "./images/saturn.png"
break;
case "uranus":
gravity = 8.69;
planetName = "Uranüs";
img.src = "./images/uranus.png"
break;
case "neptune":
gravity = 11.15;
planetName = "Neptün";
img.src = "./images/neptune.png"
break;
}
const weightOnPlanet = (inputValue.value * gravity / 9.81).toFixed(2);
const result = `Your weight in the ${planetName}'${weightOnPlanet} kilogram.`;
let para = document.createElement("p")
para.id = "demo"
para.innerText = result
div.appendChild(para)
}
}
function showWrapper() {
calculateWeight()
if (div.style.display === "none") {
div.style.display = "flex"
}
else {
div.style.display = " none"
div.innerHTML = " "
}
}

@ -0,0 +1,112 @@
# Day 24 - Mini Project
## [Exercise:Solutions](#exercise-solutions)
#### [Home](../README.md) | [<< Day 23](../23_day_event.md) | [Day 25 >>](../day_25/25_day.md)
1. Develop a small application which calculate a weight of an object in a certain planet. The gif image is not complete check the video in the starter file.
```js
// app.js
// select element
const button = document.querySelector("#button")
const div = document.getElementById("wrapper")
div.style.display = "none"
// event listener
eventListener()
function eventListener() {
button.addEventListener("click", showWrapper)
}
// calculate weight on planets
function calculateWeight() {
const inputValue = document.querySelector("#input-value")
const planet = document.querySelector("#planetName")
if(!typeof inputValue === Number || inputValue.value == "" ){
alert("geçersiz deger")
}
else{
const img = document.createElement("img")
div.appendChild(img)
let gravity;
let planetName;
switch (planet.value) {
case "mercury":
gravity = 3.7;
planetName = "Merkür";
img.src = "./images/mercury.png"
break;
case "venus":
gravity = 8.87;
planetName = "Venüs";
img.src = "./images/venus.png"
break;
case "earth":
gravity = 9.81;
planetName = "Dünya";
img.src = "./images/earth.png"
break;
case "mars":
gravity = 3.711;
planetName = "Mars";
img.src = "./images/mars.png"
break;
case "jupiter":
gravity = 24.79;
planetName = "Jüpiter";
img.src = "./images/jupiter.png"
break;
case "saturn":
gravity = 10.44;
planetName = "Satürn";
img.src = "./images/saturn.png"
break;
case "uranus":
gravity = 8.69;
planetName = "Uranüs";
img.src = "./images/uranus.png"
break;
case "neptune":
gravity = 11.15;
planetName = "Neptün";
img.src = "./images/neptune.png"
break;
}
const weightOnPlanet = (inputValue.value * gravity / 9.81).toFixed(2);
const result = `Your weight in the ${planetName}'${weightOnPlanet} kilogram.`;
let para = document.createElement("p")
para.id = "demo"
para.innerText = result
div.appendChild(para)
}
}
function showWrapper() {
calculateWeight()
if (div.style.display === "none") {
div.style.display = "flex"
}
else {
div.style.display = " none"
div.innerHTML = " "
}
}
```
<img src="./solar.png">

Binary file not shown.

After

Width:  |  Height:  |  Size: 378 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 343 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 364 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 491 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 322 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 421 KiB

@ -0,0 +1,52 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SOLAR SYSTEM</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h3>Calculate a weight of an object on a planet</h3>
<div>
<form>
<input id="input-value" type="number" name="input-value" placeholder="Your Weight">
<select name="planet" id="planetName">
<option value="mercury">mercury</option>
<option value="venus">venus</option>
<option value="earth">earth</option>
<option value="jupiter">jupiter</option>
<option value="mars">mars</option>
<option value="saturn">saturn</option>
<option value="uranus">uranus</option>
<option value="saturn">saturn</option>
<option value="neptune">neptune</option>
</select>
<input id="button" type="button" value="calculate">
</form>
</div>
<div id="wrapper" >
<!-- <img src="./images/earth.png" alt=""> -->
<!-- <p id ="demo" >merhaba ben bir uyarı kutusuyum</p> -->
</div>
<script src="app.js"></script>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 476 KiB

@ -0,0 +1,84 @@
*{
text-align: center;
font-family: sans-serif;
box-sizing: border-box;
}
body{
background-image: url("./images/galaxy.gif");
height: 100vh;
margin: 0;
}
h3{
color: #fff;
font-size: 36px;;
}
form{
display: flex;
flex-direction: column;
flex: 20px;
}
form > input{
flex: 25px;
border: 1px solid rebeccapurple;
border-radius: 5px;
margin: 5px;
padding: 25px;
box-sizing: border-box;
}
#planetName{
flex: 25px;
margin: 5px;
padding: 25px;
background-color: rgb(194, 150, 150);
border-radius: 5px;
}
#button{
text-align:center;
margin: 5px;
}
#wrapper{
display:flex;
flex-direction:row;
justify-content:center;
align-content: center;
background-color:#ffffff;
opacity: 0.6;
margin: 300px 20px;
flex-wrap: wrap;
}
#wrapper > img{
width: 200px;
height: 200px;
margin: 20px;
}
#wrapper > p{
background-color: aquamarine;
display: flex;
text-align: center;
align-items: center;
margin-left: 80px;
padding: 20px;
}
@media screen and (max-width:600px){
#wrapper > p{
display: flex;
flex-direction: column;
width: 100%;
flex-wrap:wrap;
margin: 15px 0;
}
#wrapper{
display: flex;
flex-direction: column;
margin-top:20px;
}
#wrapper img{
margin: 0 auto;
}
}

@ -0,0 +1,114 @@
# Day 25 - Mini Project
## [Exercise:Solutions](#exercise-solutions)
#### [Home](../README.md) | [<< Day 24](../day_24/day_24.md) | [Day 26 >>](../day_26/26_day_World_2.md)
### Exercise: Level 1
1. Visualize the ten most populated countries and the ten most spoken languages in the world using DOM(HTML, CSS, JS)
<img src="day25_level1.png">
### Exercise Level 1
```js
//app.js
const countryApiUrl = 'https://restcountries.com/v2/all';
const ctx = document.getElementById('population');
const ctxx = document.getElementById('langue');
const lan = document.getElementById("lan")
const country = document.getElementById("country")
let chartData = []; // Grafik verilerini saklamak için boş bir dizi
const countryName = []
let Word=0
// Grafik oluşturuluyor
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: 'Country Poplulation',
data: ["word"],
borderWidth: 1
}]
},
options: {
indexAxis: 'y',
}
});
fetch(countryApiUrl)
.then(response => response.json())
.then(data => {
console.log(data)
const arr= data.sort((a,b) =>b.population-a.population)
arr.forEach((country, index) => {
Word += country.population
if (index < 10) {
chartData.push(country.population);
countryName.push(country.name)
}
});
chartData.unshift(Word)
countryName.unshift("word")
console.log(Word)
// Verileri güncelleyip grafik yeniden çiziliyor
myChart.data.datasets[0].data = chartData;
myChart.data.labels=countryName
myChart.update();
})
.catch(err => console.log(err));
const langues = []
const langue = new Chart(ctxx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: 'Most Langue',
data: [],
borderWidth: 1
}]
},
options: {
indexAxis: 'y',
}
});
fetch(countryApiUrl)
.then((response)=> response.json())
.then((data)=>{
const langs = data.map((country) => country.languages[0].name );
console.log(typeof langs)
const counts = {};
langs.forEach((lang) => {
if (counts[lang]) {
counts[lang]++;
} else {
counts[lang] = 1;
}
});
const sortedLangs = Object.entries(counts).sort((a, b) => b[1] - a[1]).map(a => a[0]);
langue.data.labels = sortedLangs.slice(0,10);
langue.data.datasets[0].data = sortedLangs.map((lang) => counts[lang]);
langue.update();
});
function displayCountry(){
country.style.display="flex"
lan.style.display="none"
}
function displayLan(){
country.style.display="none"
lan.style.display="flex"
}
```

@ -0,0 +1,95 @@
const countryApiUrl = 'https://restcountries.com/v2/all';
const ctx = document.getElementById('population');
const ctxx = document.getElementById('langue');
const lan = document.getElementById("lan")
const country = document.getElementById("country")
let chartData = []; // Grafik verilerini saklamak için boş bir dizi
const countryName = []
let Word=0
// Grafik oluşturuluyor
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: 'Country Poplulation',
data: ["word"],
borderWidth: 1
}]
},
options: {
indexAxis: 'y',
}
});
fetch(countryApiUrl)
.then(response => response.json())
.then(data => {
console.log(data)
const arr= data.sort((a,b) =>b.population-a.population)
arr.forEach((country, index) => {
Word += country.population
if (index < 10) {
chartData.push(country.population);
countryName.push(country.name)
}
});
chartData.unshift(Word)
countryName.unshift("word")
console.log(Word)
// Verileri güncelleyip grafik yeniden çiziliyor
myChart.data.datasets[0].data = chartData;
myChart.data.labels=countryName
myChart.update();
})
.catch(err => console.log(err));
const langues = []
const langue = new Chart(ctxx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: 'Most Langue',
data: [],
borderWidth: 1
}]
},
options: {
indexAxis: 'y',
}
});
fetch(countryApiUrl)
.then((response)=> response.json())
.then((data)=>{
const langs = data.map((country) => country.languages[0].name );
console.log(typeof langs)
const counts = {};
langs.forEach((lang) => {
if (counts[lang]) {
counts[lang]++;
} else {
counts[lang] = 1;
}
});
const sortedLangs = Object.entries(counts).sort((a, b) => b[1] - a[1]).map(a => a[0]);
langue.data.labels = sortedLangs.slice(0,10);
langue.data.datasets[0].data = sortedLangs.map((lang) => counts[lang]);
langue.update();
});
function displayCountry(){
country.style.display="flex"
lan.style.display="none"
}
function displayLan(){
country.style.display="none"
lan.style.display="flex"
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

@ -0,0 +1,34 @@
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<title>JavaScript for Everyone:DOM</title>
</head>
<body>
<div class="container">
<div class="header">
<h1>World Countries Data</h1>
<p>Current we have 250 countries</p>
</div>
<div class="button-wrapper">
<button class="btn" onclick="displayCountry()">POPULATİON</button>
<button class="btn" onclick="displayLan()">LANGUES</button>
</div>
<div class="chart-wrapper">
<div id="country">
<p>10 Most populated countries in the World</p>
<canvas id="population" class="graf"></canvas>
</div>
<div id="lan">
<p>10 Most spoken langues in the World</p>
<canvas id="langue" class="graf" ></canvas>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-horizontalBar"></script>
<script src="app.js"></script>
</body>
</html>

@ -0,0 +1,65 @@
*{
box-sizing: border-box;
margin: 0;
padding: 0;
}
.container{
display: flex;
flex-direction: column;
align-content: space-around;
align-items: center;
align-content: space-around;
flex-wrap: wrap;
margin: 10px 10px;
}
.header{
display: flex;
flex-direction: column;
background-color: #f0f0f0;
width: 100%;
height: 50px;
justify-content: center;
align-items: center;
}
.header h1{
color:chocolate;
}
.button-wrapper{
display: flex;
justify-content: center;
align-items: center;
}
.btn {
background-color: chocolate;
font-size: 18px;
text-align: center;
cursor: pointer;
outline: none;
transition: .3s ease all;
margin: 15px 15px;
color: #fff;
}
.chart-wrapper{
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
width: 100%;
margin: 0 auto;
}
#country{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 60%;
}
#lan{
display:flex;
flex-direction: column;
justify-content: center;
align-items: center;
display: none;
width: 60%;
}

@ -0,0 +1,151 @@
# Day 26 - Mini Project 2
## [Exercise:Solutions](#exercise-solutions)
#### [Home](../README.md) | [<< Day 25](../day_25/25_day.md) | [Day 27 >>](../day_27/27_day_portfolio.md)
### Exercise Level 1
1. Visualize the countries array as follows
<img src="day26_miniproject2.png">
### Exercise Level 1
```js
//app.js
const countryApiUrl = 'https://restcountries.com/v2/all';
let startButton = document.getElementById("start");
let anyButton = document.getElementById("any");
const sort = document.getElementById("sort");
const input = document.getElementById("filter");
const form = document.getElementById("form")
const list = document.getElementById("list")
const text = document.getElementById("text")
let countries = [];
let filteredCountries = [];
startButton = false
anyButton = true
addEventListener();
function addEventListener() {
form.addEventListener("click",choseButton)
}
// fetchging data
fetch(countryApiUrl)
.then((response) => response.json())
.then(async (data) => {
await data.forEach((element) => {
countries.push(element.name);
});
// display(filteredCountries);
});
// display arr metod in the HTML
function display(arr) {
let dizi = []
arr.map((ar) => {
const li = `<li>${ar}</li>`;
dizi.push(li)
});
list.innerHTML=dizi
sort.addEventListener("click",(e)=>{
e.preventDefault()
list.innerHTML = dizi.reverse();
})
}
//chose buttton whick filter aray
function choseButton(e){
input.addEventListener("keyup", filterAny);
switch(e.target.id){
case "start":
e.preventDefault()
filterStart()
break;
case "any":
e.preventDefault()
filterAny()
break;
}
}
// filter array on click any button
function filterAny(){
let inputValue = input.value.toLowerCase().trim()
list.innerHTML = '';
filteredCountries = []
if(inputValue.length !==0){
countries.forEach((country)=>{
if(country.toLowerCase().trim().includes(inputValue,0)){
filteredCountries.push(country)
}else{
// console.log("Aradığınız ülke bulunamadı")
}
})
text.innerHTML=`Countries containing ${inputValue} are ${filteredCountries.length}`
}else{
// alert("Lütfen geçerli bir değer girin")
}
display(filteredCountries)
}
// filter array on click start button
function filterStart(){
let inputValue = input.value.toLowerCase().trim()
list.innerHTML = '';
filteredCountries = []
if(inputValue.length !==0){
countries.forEach((country)=>{
if(country.toLowerCase().trim().startsWith(inputValue,0)){
filteredCountries.push(country)
}else{
// console.log("Aradığınız ülke bulunamadı")
}
})
text.innerHTML=`Countries start with ${inputValue} are ${filteredCountries.length}`
}else{
// alert("Lütfen geçerli bir değer girin")
}
display(filteredCountries)
}
```

@ -0,0 +1,134 @@
const countryApiUrl = 'https://restcountries.com/v2/all';
let startButton = document.getElementById("start");
let anyButton = document.getElementById("any");
const sort = document.getElementById("sort");
const input = document.getElementById("filter");
const form = document.getElementById("form")
const list = document.getElementById("list")
const text = document.getElementById("text")
let countries = [];
let filteredCountries = [];
startButton = false
anyButton = true
addEventListener();
function addEventListener() {
form.addEventListener("click",choseButton)
}
// fetchging data
fetch(countryApiUrl)
.then((response) => response.json())
.then(async (data) => {
await data.forEach((element) => {
countries.push(element.name);
});
// display(filteredCountries);
});
// display arr metod in the HTML
function display(arr) {
let dizi = []
arr.map((ar) => {
const li = `<li>${ar}</li>`;
dizi.push(li)
});
list.innerHTML=dizi
sort.addEventListener("click",(e)=>{
e.preventDefault()
list.innerHTML = dizi.reverse();
})
}
//chose buttton whick filter aray
function choseButton(e){
input.addEventListener("keyup", filterAny);
switch(e.target.id){
case "start":
e.preventDefault()
filterStart()
break;
case "any":
e.preventDefault()
filterAny()
break;
}
}
// filter array on click any button
function filterAny(){
let inputValue = input.value.toLowerCase().trim()
list.innerHTML = '';
filteredCountries = []
if(inputValue.length !==0){
countries.forEach((country)=>{
if(country.toLowerCase().trim().includes(inputValue,0)){
filteredCountries.push(country)
}else{
// console.log("Aradığınız ülke bulunamadı")
}
})
text.innerHTML=`Countries containing ${inputValue} are ${filteredCountries.length}`
}else{
// alert("Lütfen geçerli bir değer girin")
}
display(filteredCountries)
}
// filter array on click start button
function filterStart(){
let inputValue = input.value.toLowerCase().trim()
list.innerHTML = '';
filteredCountries = []
if(inputValue.length !==0){
countries.forEach((country)=>{
if(country.toLowerCase().trim().startsWith(inputValue,0)){
filteredCountries.push(country)
}else{
// console.log("Aradığınız ülke bulunamadı")
}
})
text.innerHTML=`Countries start with ${inputValue} are ${filteredCountries.length}`
}else{
// alert("Lütfen geçerli bir değer girin")
}
display(filteredCountries)
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 MiB

@ -0,0 +1,34 @@
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="style.css">
</head>
<div class="container">
<div class="main">
<div class="header">
<h1>WORLD COUNTRİES LİST</h1>
<h2>Total numbers of countries 250</h2>
<p id="text"></p>
</div>
<div class="form-wrapper">
<form action="" id="form">
<button class="btn" id="start">STARTİNG WORLD</button>
<button class="btn" id="any">STARTİNG WİTH ANY WORLD</button>
<button class="btn" id="sort"><i class="fa-solid fa-arrow-up-a-z"></i></button>
<div class="search">
<input type="text" id="filter" placeholder="search country" style="text-align: center;">
<button id="search"> <i class="fa-solid fa-magnifying-glass"></i></button>
</div>
</form>
</div>
</div>
</div>
<div id="list" class="country-wrapper">
</div>
<script src="app.js"></script>

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

@ -0,0 +1,106 @@
*{
margin: 0;
padding: 0;
font-family: sans-serif,'Courier New', Courier, monospace;
/* border: 1px solid; */
}
.container{
background-image: url("./globe-2.jpg");
background-repeat: no-repeat;
background-size:100% 60vh;
object-fit: cover;
height: 60vh;
display: flex;
justify-content: center;
align-items: center;
object-position: 40% 60%;
}
.main{
width: 100%;
}
h1{
width: 100%;
text-align: center;
letter-spacing: 0.3em;
}
.btn{
background-color: blueviolet;
color: white;
border-radius: 8px;
padding: 12px 15px;
font-weight: 100;
font-weight: bold;
font-size: x-large;
}
.btn:hover{
background-color: rgb(42, 165, 118);
}
.header{
display: flex;
flex-direction: column;
align-items: center;
}
.header h1{
margin-bottom: 20px;
font-size:400%;
color:aliceblue
}
.header h2{
color: rgb(0, 0, 0);
font-size:200%;
margin-bottom:20px
}
.header p{
font-weight: bold;
font-size:x-large
}
.form-wrapper{
margin-top: 40px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.form-wrapper .search{
display: flex;
justify-content: center;
margin-top: 20px;
}
#search{
padding: 10px;
}
.form-wrapper .search input{
width: 100%;
margin-right: 10px;
border-radius: 10px;
padding: 3px 0;
border: none;
padding: 10px 10px;
}
.country-wrapper{
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
min-height: 40vh;
background-color: rgb(127, 235, 206);
}
li{
list-style: none;
border: 1px solid;
padding: 20px 10px;
background-image: url("./map_image.jpg");
background-repeat: no-repeat;
background-size: cover;
margin: 5px;
border-radius: 5px;
border: 1px solid black;
filter: drop-shadow(2px 2px 5px green);
}

@ -0,0 +1,47 @@
# Day 27 - Portfolio
## [Exercise:Solutions](#exercise-solutions)
#### [Home](../README.md) | [<< Day 26](../day_26/26_day_World_2.md) | [Day 28 >>](../day_28/day_28_leaderboard.md)
### Exercise Level 1
1. Create the following using HTML, CSS, and JavaScript
<img src="./day27_portfolio.png">
```js
//app.js
const animation = document.getElementById("footer")
const header = document.getElementById("header")
const headerWords=["Motivaional Speaker","Programmer", "Educator","Content Creator","Motivator","Instructer"]
const footerWords = ["HTML", "CSS", "JavaScript", "React"];
let i = 0; // bu değişkeni genel olarak tanımlamak gerekiyor
function typeWord() {
if (i < footerWords.length) {
let currentWord = footerWords[i];
animation.innerHTML ="The tecnologies I teach " + `<span>${currentWord}</span>`
setTimeout(typeWord, 2000)
i++
} else {
i = 0;
typeWord();
}
}
typeWord();
function headerAnimation(){
if(i<headerWords.length){
let currentWord=headerWords[i]
header.innerHTML=currentWord
i++
setTimeout(headerAnimation,2000)
}
else{
i=0
headerAnimation()
}
}
headerAnimation()
```

@ -0,0 +1,33 @@
const animation = document.getElementById("footer")
const header = document.getElementById("header")
const headerWords=["Motivaional Speaker","Programmer", "Educator","Content Creator","Motivator","Instructer"]
const footerWords = ["HTML", "CSS", "JavaScript", "React"];
let i = 0; // bu değişkeni genel olarak tanımlamak gerekiyor
function typeWord() {
if (i < footerWords.length) {
let currentWord = footerWords[i];
animation.innerHTML ="The tecnologies I teach " + `<span>${currentWord}</span>`
setTimeout(typeWord, 2000)
i++
} else {
i = 0;
typeWord();
}
}
typeWord();
function headerAnimation(){
if(i<headerWords.length){
let currentWord=headerWords[i]
header.innerHTML=currentWord
i++
setTimeout(headerAnimation,2000)
}
else{
i=0
headerAnimation()
}
}
headerAnimation()

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div class="header">
<div class="title">
<div class="card-wrapper">
</div>
<h1>Nevzat Atalay</h1>
</div>
<div class="header-animation" id="animation">
<p id="header"></p>
</div>
</div>
<div class="main">
<p>Hello, I'm Nevzat Atalay. I am developing the 27th project of the 30 Days Of JavaScript project.</p>
<div class="challenge">
<P class="skill">30 Days Of JavaScript</P>
<P class="skill">30 Days Of React </P>
<p class="skill">30 Days Of Phyton</p>
</div>
</div>
<div class="footer" id="footer">
</div>
</div>
<script src="app.js"></script>
</body>
</html>

@ -0,0 +1,90 @@
*{
/* border: 1px solid; */
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: sans-serif,'Times New Roman', Times, serif,monospace;
}
.container{
display: flex;
flex-direction:column;
justify-content:space-evenly;
margin: 0 10%;
height: auto;
}
/* Header CSS */
.header{
display: flex;
flex-direction: column;
justify-content:space-between;
min-height:25%;
}
.header .title{
letter-spacing: 1em;
}
.header .title .card-wrapper{
}
.header .title .card-wrapper .card{
}
.header .header-animation{
background-color:yellow;
padding: 5%;
}
h1{
font-size:600%;
letter-spacing:0.4em
}
/* Main CSS */
.main{
display: flex;
flex-direction: column;
margin-bottom:15%;
}
.main p{
margin-top: 25px;
}
.container .main .challenge{
display: flex;
flex-direction: row;
justify-content: space-around;
}
.container .main .challenge .skill{
display: flex;
padding: 75px;
align-items: center;
justify-content: center;
margin-top:5%;
border: 1px solid;
border-radius: 10px;
}
/* Footer CSS*/
span{
color:fuchsia;
font-weight: bold;
}
#header {
animation-duration: 2s;
animation-name: slidein;
animation-iteration-count: infinite;
display: inline;
font-weight: bold;
}
@keyframes slidein {
from {
margin-left: 0;
}
to {
margin-left: 10%;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

@ -0,0 +1,91 @@
const playerWrapper = document.getElementById("player-wrapper");
const personName = document.getElementById("input-first-name");
const personLastName = document.getElementById("input-lastname");
const personCountrt = document.getElementById("country");
const personScore = document.getElementById("score");
const form = document.getElementById("form")
class Players {
constructor(firstName, lastname, country, score) {
this.firstNamename = firstName;
this.lastname = lastname;
this.country = country;
this.score = score;
this.fullName=firstName + " " + lastname
}
display() {
playerWrapper.innerHTML += `<ul>
<li>${this.fullName}</li>
<li>${this.country}</li>
<li>${this.score}</li>
<div class="button-wrapper">
<button><i class="fa-solid fa-trash-can"></i></button>
<button><i class="fa-solid fa-plus">5</i></button>
<button><i class="fa-solid fa-minus">5</i></button>
</div>
</ul>`;
}
}
const player1 = new Players("nevzat", "Atalay", "Turkey", 100);
const player2 = new Players("ali", "veli", "Turkey", 100);
player1.display()
player2.display()
function getInformation() {
const form = document.getElementById("form")
form.addEventListener("submit",(e)=>{
e.preventDefault()
if(personName.value.length>0 && personLastName.value.length>0 && personCountrt.value.length>0 && personScore.value.length>0){
const player=new Players(personName.value,personLastName.value,personCountrt.value,personScore.value)
player.display()
}else{
alert("Lütfen eksik bilgileri tamamlayınız.")
}
personName.value=""
personLastName.value=""
personCountrt.value=""
personScore.value=""
})
}
getInformation();
function editPerson(){
playerWrapper.addEventListener("click",(e)=>{
if(e.target.className=="fa-solid fa-trash-can"){
const ul = e.target.parentElement.parentElement.parentElement
ul.remove()
}
})
}
editPerson()
function editPersonScore() {
playerWrapper.addEventListener("click", (e) => {
if (e.target.className === "fa-solid fa-plus") {
let li = e.target.parentElement.parentElement.parentElement.children[2];
let num = parseInt(li.innerText);
if(num<100){
num += 5;
li.innerText = num
}else{
alert("You have max score")
}
} else if (e.target.className === "fa-solid fa-minus") {
let li = e.target.parentElement.parentElement.parentElement.children[2];
let num = parseInt(li.innerText)
if(num>5){
num-=5
li.innerText=num
}else{
alert("You have minimum score")
}
}
});
}
editPersonScore();

@ -0,0 +1,107 @@
# Day 28 - Portfolio
## [Exercise:Solutions](#exercise-solutions)
#### [Home](../README.md) | [<< Day 27](../day_27/27_day_portfolio.md) | [Day 29 >>](../day_29/29_day_animatingcharecter.md)
### Exercise Level 1
1. Create the following using HTML, CSS, and JavaScript
<img src="Ekran görüntüsü_2024-06-13_19-33-46.png">
```js
//app.js
const playerWrapper = document.getElementById("player-wrapper");
const personName = document.getElementById("input-first-name");
const personLastName = document.getElementById("input-lastname");
const personCountrt = document.getElementById("country");
const personScore = document.getElementById("score");
const form = document.getElementById("form")
class Players {
constructor(firstName, lastname, country, score) {
this.firstNamename = firstName;
this.lastname = lastname;
this.country = country;
this.score = score;
this.fullName=firstName + " " + lastname
}
display() {
playerWrapper.innerHTML += `<ul>
<li>${this.fullName}</li>
<li>${this.country}</li>
<li>${this.score}</li>
<div class="button-wrapper">
<button><i class="fa-solid fa-trash-can"></i></button>
<button><i class="fa-solid fa-plus">5</i></button>
<button><i class="fa-solid fa-minus">5</i></button>
</div>
</ul>`;
}
}
const player1 = new Players("nevzat", "Atalay", "Turkey", 100);
const player2 = new Players("ali", "veli", "Turkey", 100);
player1.display()
player2.display()
function getInformation() {
const form = document.getElementById("form")
form.addEventListener("submit",(e)=>{
e.preventDefault()
if(personName.value.length>0 && personLastName.value.length>0 && personCountrt.value.length>0 && personScore.value.length>0){
const player=new Players(personName.value,personLastName.value,personCountrt.value,personScore.value)
player.display()
}else{
alert("Lütfen eksik bilgileri tamamlayınız.")
}
personName.value=""
personLastName.value=""
personCountrt.value=""
personScore.value=""
})
}
getInformation();
function editPerson(){
playerWrapper.addEventListener("click",(e)=>{
if(e.target.className=="fa-solid fa-trash-can"){
const ul = e.target.parentElement.parentElement.parentElement
ul.remove()
}
})
}
editPerson()
function editPersonScore() {
playerWrapper.addEventListener("click", (e) => {
if (e.target.className === "fa-solid fa-plus") {
let li = e.target.parentElement.parentElement.parentElement.children[2];
let num = parseInt(li.innerText);
if(num<100){
num += 5;
li.innerText = num
}else{
alert("You have max score")
}
} else if (e.target.className === "fa-solid fa-minus") {
let li = e.target.parentElement.parentElement.parentElement.children[2];
let num = parseInt(li.innerText)
if(num>5){
num-=5
li.innerText=num
}else{
alert("You have minimum score")
}
}
});
}
editPersonScore();
```

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<div class="container">
<div class="header">
<div class="title">
<h3>30 Days Of JavaScript Challenge Leaderboard </h3>
</div>
<div class="form-wrapper">
<form id="form">
<div id="iputs">
<input type="text" id="input-first-name" placeholder="firs name">
<input type="text" id="input-lastname" placeholder="last name">
<input type="text" id="country" placeholder="country">
<input type="number" id="score" placeholder="score">
</div>
<button type="submit">Add Player</button>
</form>
</div>
</div>
<div class="main" id="player-wrapper">
<!-- <ul>
<li>name </li>
<li>country</li>
<li>scor</li>
<div class="button-wrapper">
<button><i class="fa-solid fa-trash-can"></i></button>
<button><i class="fa-solid fa-plus">5</i></button>
<button><i class="fa-solid fa-minus">5</i></button>
</div>
</ul> -->
</div>
</div>
<script src="app.js"></script>
</body>
</html>

@ -0,0 +1,90 @@
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: sans-serif,'Times New Roman', Times, serif;
/* border: 1px solid; */
}
.container{
display: flex;
flex-direction: column;
justify-content: center;
height: 100vh;
}
/* Header CSS*/
.container .header{
display: flex;
flex-direction: column;
height: 25%;
justify-content: space-around;
}
.container .header .title h3{
text-align: center;
}
.container .header .form-wrapper{
width: 60%;
margin: 0 auto;
}
.container .header .form-wrapper form{
display: flex;
flex-direction: row;
justify-content: space-between;
}
.container .header .form-wrapper form input{
padding: 5px 14px;
width: 23%;
}
/* Main CSS*/
.main{
display: flex;
flex-direction: column;
}
.main ul{
display: flex;
flex-direction: row;
border: 1px solid;
justify-content:space-between;
width: 60%;
margin: 0 auto;
background-color: thistle;
margin-bottom: 5px;
}
.main ul li{
list-style: none;
padding: 10px 20px;
flex-wrap: wrap;
width: 20%;
}
.main .button-wrapper{
display: flex;
justify-content: center;
align-items: center;
width: 25%;
text-align: center;
}
.main .button-wrapper button{
border-radius: 50%;
padding: 5px;
background-color: aqua;
}
.main .button-wrapper button:hover{
background-color: tomato;
}
@media screen and (max-width:600px){
.main .button-wrapper button{
padding: 2px;
}
.main ul{
width: 100%;
}
.container .header .form-wrapper{
width: 100%;
}
}

@ -0,0 +1,47 @@
# Day 29 - Portfolio
## [Exercise:Solutions](#exercise-solutions)
#### [Home](../README.md) | [<< Day 28](../day_28/day_28_leaderboard.md) | [Day 30 >>](../day_30/30_day_finalprohects.md)
### Exercise Level 1
1. Create the following using HTML, CSS, and JavaScript
<img src="Ekran görüntüsü_2024-07-07_09-25-50.png">
```js
// app.js
const header = document.getElementById("header")
let sentences="30 DAYS OF JAVASCRİPT CHALLENGE 2023 NEVZAT ATALAY"
function displayLetters(){
const container = document.getElementById("container").style.setProperty("background-color", randomColor())
let words = sentences.split(" ")
let p = ""
for(i=0; i<words.length; i++){
for(let j=0; j<words[i].length; j++){
p+= `<span style="color:${randomColor()}">${words[i][j]}</span>`
}
}
console.log(p)
return header.innerHTML=p
}
function randomColor() {
let hexa = "#"
let letters = "0123456789ABCDEF"
for(let i=0; i<6; i++){
let randomNumber = Math.floor(Math.random() * letters.length)
hexa += letters[randomNumber]
}
return hexa
}
setInterval(displayLetters,1000)
```

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

@ -0,0 +1,30 @@
const header = document.getElementById("header")
let sentences="30 DAYS OF JAVASCRİPT CHALLENGE 2023 NEVZAT ATALAY"
function displayLetters(){
const container = document.getElementById("container").style.setProperty("background-color", randomColor())
let words = sentences.split(" ")
let p = ""
for(i=0; i<words.length; i++){
for(let j=0; j<words[i].length; j++){
p+= `<span style="color:${randomColor()}">${words[i][j]}</span>`
}
}
console.log(p)
return header.innerHTML=p
}
function randomColor() {
let hexa = "#"
let letters = "0123456789ABCDEF"
for(let i=0; i<6; i++){
let randomNumber = Math.floor(Math.random() * letters.length)
hexa += letters[randomNumber]
}
return hexa
}
setInterval(displayLetters,1000)

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<h1 id="header"></h1>
</div>
<script src="app.js"></script>
</body>
</html>

@ -0,0 +1,13 @@
*{
margin: 0;
padding: 0;
}
#container{
height: 100vh;
}
#header{
display: flex;
line-height: 2em;
font-size: 4em;
flex-wrap: wrap;
}

@ -0,0 +1,12 @@
# Day 30 - Portfolio
## [Exercise:Solutions](#exercise-solutions)
#### [Home](../README.md) | [<< Day 29](../day_29/29_day_animatingcharecter.md) | [Home>>](../../README.md)
### Exercise Level 1
1. Create the following using HTML, CSS, and JavaScript
<img src="Ekran görüntüsü_2024-07-07_09-28-08.png">

Binary file not shown.

After

Width:  |  Height:  |  Size: 283 KiB

@ -0,0 +1,251 @@
const main = document.getElementById("main");
const form = document.getElementById("search");
const input = document.getElementById("input");
let ctx = document.getElementById('myChart');
const graphic = document.getElementById("graphic")
const icon = document.getElementById('icon')
let filteredCountries = [];
let countriesPopulation = [];
let mostSpekingLangue = new Map();
calculateMostSpeakingLangues(countriesData)
createCardAndDisplay(sortCountriesToCountriName(countriesData))
// create carts and display in HTML function
function createCardAndDisplay(arr){
let cards = [];
arr.forEach((data) => {
countriesPopulation.push(data.population)
let card = `
<div class = "country-wrapper">
<img src = "${data.flag}">
<p class = "country-name">${data.name } </p>
<ul>
<li>Capital: ${data.capital} </li>
<li>Langue: ${data.languages} </li>
<li>Population: ${data.population} </li>
<ul>
</div>
`;
cards.push(card)
})
main.innerHTML = ''
main.innerHTML = cards
}
// buttons click events
form.addEventListener('click', (e) => {
e.preventDefault()
let element = e.target;
if(!element.matches('button')) return;
switch(element.id){
// click reverse button
case'reverseButton':
if (input.value.length == 0){
if(main.className == "main"){
main.className = "main-reverse"
createCardAndDisplay(sortCountriesToCountriName(countriesData).reverse())
}
else if(main.className == "main-reverse"){
main.className = "main"
createCardAndDisplay(sortCountriesToCountriName(countriesData))
}
else {
main.className = 'main'
createCardAndDisplay(sortCountriesToCountriName(countriesData))
}
}
else {
if(main.className == 'filtered-countries'){
main.className = 'filtered-countries-reverse'
createCardAndDisplay(filteredCountries.reverse())
}
else if(main.className == 'filtered-countries-reverse'){
main.className = 'filtered-countries'
createCardAndDisplay(filteredCountries.reverse())
}
else{
main.className = 'filtered-countries';
createCardAndDisplay(sortCountriesToCountriName(filteredCountries))
}
}
break
// click capital button
case'capitalButton':
if(input.value.length == 0 ){
if(main.className == "main-capital"){
main.className = "main-capital-reverse"
createCardAndDisplay(sortCountriesToCapitalName(sortCountriesToCountriName(countriesData)).reverse())
}
else if(main.className == "main-capital-reverse"){
main.className = "main-capital"
createCardAndDisplay(sortCountriesToCapitalName(sortCountriesToCountriName(countriesData)))
}
else {
main.className = 'main-capital'
createCardAndDisplay(sortCountriesToCapitalName(sortCountriesToCountriName(countriesData)))
}
}
else {
if(main.className == 'filtered-capital'){
main.className = 'filtered-capital-reverse'
createCardAndDisplay(sortCountriesToCapitalName(sortCountriesToCountriName(filteredCountries)).reverse())
}
else if (main.className == 'filtered-capital-reverse'){
main.className = 'filtered-capital'
createCardAndDisplay(sortCountriesToCapitalName(sortCountriesToCountriName(filteredCountries)))
}
else{
main.className = 'filtered-capital'
createCardAndDisplay(sortCountriesToCapitalName(sortCountriesToCountriName(filteredCountries)))
}
}
break;
// click population button
case 'population-button':
if (input.value.length == 0){
if (main.className == 'main-population'){
main.className = 'main-population-reverse'
createCardAndDisplay(sortCountriesToPopulation(countriesData).reverse())
}
else if (main.className == 'main-population-reverse'){
main.className = 'main-population'
createCardAndDisplay(sortCountriesToPopulation(countriesData))
}
else {
main.className = 'main-population'
createCardAndDisplay(sortCountriesToPopulation(countriesData))
}
}
else{
if(main.className == 'filtered-population'){
main.className = 'filtered-population-reverse'
createCardAndDisplay(sortCountriesToPopulation(filteredCountries).reverse())
}
else if (main.className == 'filtered-population-reverse'){
main.className = 'filtered-population'
createCardAndDisplay(sortCountriesToPopulation(filteredCountries))
}
else {
main.className = 'filtered-population'
createCardAndDisplay(sortCountriesToPopulation(filteredCountries))
}
}
}
});
//input event listener
input.addEventListener('keyup', (e)=>{
countriesPopulation = [];
filteredCountries = [];
e.preventDefault()
let value = e.target.value.trim().toLowerCase()
if (value.length > 0){
sortCountriesToCountriName(countriesData).forEach((data) => {
if(data.name.toLowerCase().trim().startsWith(value)){
filteredCountries.push(data)
countriesPopulation.push(data.population)
}
})
main.className = 'filtered-countries'
createCardAndDisplay(filteredCountries)
updateGrapgic(sortArrayNames(filteredCountries),
sortArrays(countriesPopulation))
}
else if (value.length == 0){
main.className = 'main'
createCardAndDisplay((sortCountriesToCountriName(countriesData)))
updateGrapgic(sortArrayNames(countriesData).slice(0,8),
sortArrays(countriesPopulation).slice(0,8))
}
});
// return sort countries name function
function sortArrays(arr){
return arr.sort((a, b) => {return b-a})
}
// Return the names of countries sorted by country population
function sortArrayNames (arr){
let countriesName = [];
sortCountriesToPopulation(arr).forEach((data)=>{
countriesName.push(data.name)
})
return countriesName;
}
// return sort countries data array by countries name
function sortCountriesToCountriName(arr) {
return arr.sort((a, b) =>{
if(a.name < b.name) return -1;
if(a.name > b.name) return +1;
return 0;
});
}
// return sort capital name
function sortCountriesToCapitalName(arr) {
return arr.sort((a, b) =>{
if(a.capital == undefined ) return -1
if(a.capital < b.capital) return -1;
if(a.capital > b.capital) return +1;
return 0;
});
}
// return sort populations
function sortCountriesToPopulation (arr) {
return arr.sort((a, b) => {
if(a.population < b.population) return +1
if(a.population > b.population) return -1
return 0;
});
}
// Object for graphic
let myCharts = new Chart(ctx, {
type: 'bar',
data: {
labels:sortArrayNames(countriesData).slice(0,8),
datasets: [{
label: '# of Votes',
data:sortArrays(countriesPopulation).slice(0,8),
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
// update graphic when pressing keyboard
function updateGrapgic(countriesNames, countriesPopulations) {
myCharts.data.labels = countriesNames;
myCharts.data.datasets[0].data = countriesPopulations;
myCharts.update()
}
icon.addEventListener('click', ()=> {
graphic.classList.toggle('graphic-wrapper')
})
function calculateMostSpeakingLangues(array) {
array.forEach((data) =>{
mostSpekingLangue.set(data.languages,data.name)
})
}

@ -0,0 +1,49 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
</head>
<body>
<div id="demo" class="container">
<div class="header">
<h3>World Countries Data</h3>
<p>Current we have 250 countries</p>
<form action="" id="search">
<input type="text" id="input" >
<div class="button-wrapper">
<button type="submit" id="reverseButton">name</button>
<button type="submit" id="capitalButton">capital</button>
<button type="submit" id="population-button">population</button>
</div>
<hr>
</form>
<a href="#graphic" id="icon"> <img class="icon" src="statistics.png" alt=""></a>
</div>
<div id="main" class="main">
</div>
<div id="graphic" class="graphic-wrapper2">
<div>
<button>langue</button>
<button>population</button>
</div>
<canvas id="myChart"></canvas>
<a href="#top" class="arrow"><i class="fa-solid fa-arrow-up "></i></a>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="../data/countries_data.js"></script>
<script src="../data/countries.js"></script>
<script src="app.js" ></script>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

@ -0,0 +1,112 @@
*{
margin: 0;
padding: 0;
font-family: sans-serif,'Times New Roman', Times, serif;
/* border: 1px solid; */
}
body{
background-color: rgb(32, 220, 160);
}
.container{
display: flex;
flex-wrap: wrap;
margin-top: 25px;
}
.container .header{
display: flex;
flex-direction: column;
justify-content: space-evenly;
align-items: center;
width: 100%;
margin: 0 auto;
}
h3{
font-size:400%
}
p{
font-size: 200%;
}
.container .header form{
display: flex;
flex-direction: column;
width: 60%;
justify-content: space-around;
}
.container .header form input{
padding: 10px 20px;
border-radius:10px;
font-size:x-large
}
.container .header .button-wrapper{
display: flex;
flex-direction: row;
justify-content: space-evenly;
margin-top:15px;
margin-bottom:10px;
}
button{
border-radius: 10px;
background-color: rgb(37, 156, 220);
padding: 15px 35px;
color:aliceblue;
font-size:large;
}
/* main css*/
.container .main, .main-reverse, .filtered-countries,
.filtered-countries-reverse, .main-capital, .main-capital-reverse,
.filtered-capital, .filtered-capital-reverse, .main-population,
.main-population-reverse, .filtered-population,
.filtered-population-reverse{
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
}
.container .country-wrapper{
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
width: 120px;
background-color: aliceblue;
margin: 5px;
padding: 10px 0;
}
.container .country-wrapper img{
margin: 5px 0;
width: 80%;
}
.container .country-wrapper p{
font-size: x-large;
margin-top: 5px;
}
.icon{
width: 60px;
}
.container .country-wrapper ul{
width: 80%;
list-style: none;
}
.container .country-wrapper ul li{
font-size: 1em;
}
.graphic-wrapper2{
display: none;
}
.graphic-wrapper{
display:flex;
width: 80%;
justify-content: center;
align-items: center;
flex-direction: column;
margin:30px auto ;
}
.fa-solid{
padding: 50px;
font-size: 50px;
}
Loading…
Cancel
Save