diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 0000000..6f3a291
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,3 @@
+{
+ "liveServer.settings.port": 5501
+}
\ No newline at end of file
diff --git a/01_JS_Basics/Ch1_pgm_01.js b/01_JS_Basics/Ch1_pgm_01.js
index 55f4b51..4f6b3a1 100644
--- a/01_JS_Basics/Ch1_pgm_01.js
+++ b/01_JS_Basics/Ch1_pgm_01.js
@@ -1,6 +1,7 @@
// Using console.log to display information
-console.log("Hello World!");
+console.log("your program");
+console.log("my program");
/* Further Adventures
diff --git a/02_JS_variables/Ch2_pgm_01.js b/02_JS_variables/Ch2_pgm_01.js
index 3c824c6..7d86af2 100644
--- a/02_JS_variables/Ch2_pgm_01.js
+++ b/02_JS_variables/Ch2_pgm_01.js
@@ -1,6 +1,8 @@
// Declaring a variable
var score;
+var variable1;
+var variable2;
/* Further Adventures
*
diff --git a/02_JS_variables/Ch2_pgm_02.js b/02_JS_variables/Ch2_pgm_02.js
index 6fd81c2..0e7b248 100644
--- a/02_JS_variables/Ch2_pgm_02.js
+++ b/02_JS_variables/Ch2_pgm_02.js
@@ -2,6 +2,11 @@
var score;
score = 100;
+console.log(score);
+score=200;
+console.log(score);
+score=300;
+console.log(score);
/* Further Adventures
*
@@ -17,7 +22,7 @@ score = 100;
* 3) Type the word score to match your variable name
* and press enter.
* 100, the value assigned to score, should be displayed.
- *
+ *
* 4) Change the value of score in the code above.
* Repeat steps 1, 2 and 3.
*
diff --git a/02_JS_variables/Ch2_pgm_03.js b/02_JS_variables/Ch2_pgm_03.js
index cc61b9f..94f819d 100644
--- a/02_JS_variables/Ch2_pgm_03.js
+++ b/02_JS_variables/Ch2_pgm_03.js
@@ -3,6 +3,11 @@
var score;
score = 100;
console.log(score);
+score = 1004
+console.log(score);
+var score2;
+score2 = 190;
+console.log(score2);
diff --git a/02_JS_variables/Ch2_pgm_04.js b/02_JS_variables/Ch2_pgm_04.js
index 6ae5ad7..49e124a 100644
--- a/02_JS_variables/Ch2_pgm_04.js
+++ b/02_JS_variables/Ch2_pgm_04.js
@@ -7,8 +7,11 @@ console.log(score);
score = 150;
console.log(score);
-
-
+var score2;
+score2 = 190;
+console.log(score2);
+score2 = 277;
+console.log(score2);
/* Further Adventures
*
* 1) Change the value assigned to score.
diff --git a/02_JS_variables/Ch2_pgm_05.js b/02_JS_variables/Ch2_pgm_05.js
index 44b7399..6dfcdfa 100644
--- a/02_JS_variables/Ch2_pgm_05.js
+++ b/02_JS_variables/Ch2_pgm_05.js
@@ -8,6 +8,14 @@ console.log(message);
message = 'Congratulations! Your tweet has won a prize...';
console.log(message);
+message = "Thank You!";
+console.log(message);
+
+message = "Hello " + "World!";
+console.log(message)
+message = 'Congratulations!' + ' Your' + ' tweet has won a prize...';
+console.log(message);
+
/* Further Adventures
diff --git a/02_JS_variables/Ch2_pgm_06.js b/02_JS_variables/Ch2_pgm_06.js
index a8196ef..c3f229a 100644
--- a/02_JS_variables/Ch2_pgm_06.js
+++ b/02_JS_variables/Ch2_pgm_06.js
@@ -7,7 +7,9 @@ playerName = "Lionel Messi";
locationName = "Argentina";
console.log(playerName + " is in " + locationName);
-
+var score;
+score = 100;
+console.log(playerName + " has a score of " + score);
/* Further Adventures
diff --git a/02_JS_variables/Ch2_pgm_07.js b/02_JS_variables/Ch2_pgm_07.js
index 37e048d..a59d0f5 100644
--- a/02_JS_variables/Ch2_pgm_07.js
+++ b/02_JS_variables/Ch2_pgm_07.js
@@ -2,10 +2,11 @@
var playerName = "Kandra";
var locationName = "The Dungeon of Doom";
-
console.log(playerName + " is in " + locationName);
-
-
+var health = 50;
+console.log(playerName + " has health " + health + " and is in " + locationName);
+var message = playerName + " has health " + health + " and is in " + locationName;
+console.log(message);
/* Further Adventures
*
diff --git a/02_JS_variables/Ch2_pgm_08.js b/02_JS_variables/Ch2_pgm_08.js
index 6d039cb..9cee6e0 100644
--- a/02_JS_variables/Ch2_pgm_08.js
+++ b/02_JS_variables/Ch2_pgm_08.js
@@ -10,6 +10,12 @@ console.log("New score: " + score);
console.log("Way to go!");
+// Further adventures
+console.log("Successful splat of a kumquat!");
+score = score + 100;
+console.log("New score: " + score);
+console.log("Congratulations!");
+
/* Further Adventures
diff --git a/02_JS_variables/Ch2_pgm_09.js b/02_JS_variables/Ch2_pgm_09.js
index 2f5d672..3ce75e9 100644
--- a/02_JS_variables/Ch2_pgm_09.js
+++ b/02_JS_variables/Ch2_pgm_09.js
@@ -6,11 +6,6 @@ var _underscore56;
var StartWithCapital;
var z5;
-var 999;
-var 39Steps;
-var &nope;
-var single words only;
-var yield;
diff --git a/03_JS_Objects/Ch3_pgm_01.js b/03_JS_Objects/Ch3_pgm_01.js
index 2627373..be12704 100644
--- a/03_JS_Objects/Ch3_pgm_01.js
+++ b/03_JS_Objects/Ch3_pgm_01.js
@@ -8,6 +8,39 @@ bookAuthor = "J. R. R. Tolkien";
console.log(bookTitle + " by " + bookAuthor);
+// Book-2
+var bookTitle2;
+var bookAuthor2;
+
+bookTitle2 = "Four Stars of Destiny";
+bookAuthor2 = "General Manoj Mukund Naravane";
+
+console.log(bookTitle2 + " by " + bookAuthor2);
+
+// Book-3
+var bookTitle3;
+var bookAuthor3;
+
+bookTitle3 = "Spare";
+bookAuthor3 = "J. R. Moehringer";
+console.log(bookTitle3 + " by " + bookAuthor3);
+
+// Book-4
+var bookTitle4;
+var bookAuthor4;
+
+bookTitle4 = "Victory City";
+bookAuthor4 = "Salman Rushdie";
+console.log(bookTitle4 + " by " + bookAuthor4);
+
+// Book-5
+var bookTitle5;
+var bookAuthor5;
+
+bookTitle5 = "As Good As My Word";
+bookAuthor5 = "KM Chandrashekhar";
+console.log(bookTitle5 + " by " + bookAuthor5);
+
/* Further Adventures
diff --git a/03_JS_Objects/Ch3_pgm_02.js b/03_JS_Objects/Ch3_pgm_02.js
index d2be7f8..a5440d1 100644
--- a/03_JS_Objects/Ch3_pgm_02.js
+++ b/03_JS_Objects/Ch3_pgm_02.js
@@ -14,6 +14,17 @@ console.log(book1Title + " by " + book1Author);
console.log(book2Title + " by " + book2Author);
console.log(book3Title + " by " + book3Author);
+// Adding Book-4
+
+bookTitle4 = "Victory City";
+bookAuthor4 = "Salman Rushdie";
+
+console.log("There are four books so far...");
+console.log(book1Title + " by " + book1Author);
+console.log(book2Title + " by " + book2Author);
+console.log(book3Title + " by " + book3Author);
+console.log(bookTitle4 + " by " + bookAuthor4);
+
/* Further Adventures
diff --git a/03_JS_Objects/Ch3_pgm_03.js b/03_JS_Objects/Ch3_pgm_03.js
index c76a9d5..a1d056a 100644
--- a/03_JS_Objects/Ch3_pgm_03.js
+++ b/03_JS_Objects/Ch3_pgm_03.js
@@ -10,6 +10,29 @@ book = {
console.log(book);
+// Changing the title of the book
+
+var book;
+
+book = {
+ title : "The Hobbit, or There and Back Again",
+ author : "J. R. R. Tolkien",
+ published : 1937
+};
+
+console.log(book);
+
+// Adding Book-2 object
+var book;
+
+book2 = {
+ title : "Let us Dream",
+ author : "Pope Francis",
+ published : 2020
+};
+
+console.log(book2);
+
/* Further Adventures
diff --git a/03_JS_Objects/Ch3_pgm_04.js b/03_JS_Objects/Ch3_pgm_04.js
index 1127691..5004c38 100644
--- a/03_JS_Objects/Ch3_pgm_04.js
+++ b/03_JS_Objects/Ch3_pgm_04.js
@@ -3,7 +3,15 @@
var book;
book = {};
+// Console book
+console.log(book);
+// Adding extra empty lines
+book = {
+
+
+};
+console.log(book);
/* Further Adventures
*
diff --git a/03_JS_Objects/Ch3_pgm_05.js b/03_JS_Objects/Ch3_pgm_05.js
index 4d10f72..a9cbef7 100644
--- a/03_JS_Objects/Ch3_pgm_05.js
+++ b/03_JS_Objects/Ch3_pgm_05.js
@@ -5,7 +5,17 @@ var book;
book = {
title : "The Hobbit"
};
+// console book
+console.log(book);
+// Book-2
+var book2;
+
+book2 = {
+ title : "Let us Dream"
+};
+// console book-2
+console.log(book2);
/* Further Adventures
diff --git a/03_JS_Objects/Ch3_pgm_06.js b/03_JS_Objects/Ch3_pgm_06.js
index cbb1a1c..87c9f92 100644
--- a/03_JS_Objects/Ch3_pgm_06.js
+++ b/03_JS_Objects/Ch3_pgm_06.js
@@ -1,5 +1,6 @@
// Using a variable as a property value
+var book;
var book;
var bookName;
@@ -9,6 +10,12 @@ book = {
title : bookName
};
+// Changing the value for bookName
+bookName = "Victory City";
+
+book = {
+ title : bookName
+};
/* Further Adventures
diff --git a/03_JS_Objects/Ch3_pgm_07.js b/03_JS_Objects/Ch3_pgm_07.js
index e813d36..4cf059e 100644
--- a/03_JS_Objects/Ch3_pgm_07.js
+++ b/03_JS_Objects/Ch3_pgm_07.js
@@ -5,14 +5,18 @@ var book2;
book1 = {
title : "The Hobbit",
- author : "J. R. R. Tolkien"
+ author : "J. R. R. Tolkien",
+ year : 1837 //Add third property
};
book2 = {
title : "Northern Lights",
- author : "Philip Pullman"
+ author : "Philip Pullman",
+ year : 1902 //Add third property
};
-
+//Console both book objects
+console.log(book1);
+console.log(book2);
/* Further Adventures
diff --git a/03_JS_Objects/Ch3_pgm_08.js b/03_JS_Objects/Ch3_pgm_08.js
index 3b19a78..ed220e8 100644
--- a/03_JS_Objects/Ch3_pgm_08.js
+++ b/03_JS_Objects/Ch3_pgm_08.js
@@ -10,6 +10,20 @@ book = {
console.log(book.title);
console.log(book.author);
+// console published property
+console.log(book.published);
+
+// Adding Book-2
+var book2;
+
+book2 = {
+ title : "Let us Dream",
+ author : "Pope Francis",
+ published : 2020
+};
+console.log(book2.title);
+console.log(book2.author);
+console.log(book2.published);
diff --git a/03_JS_Objects/Ch3_pgm_09.js b/03_JS_Objects/Ch3_pgm_09.js
index fe04433..4b340f9 100644
--- a/03_JS_Objects/Ch3_pgm_09.js
+++ b/03_JS_Objects/Ch3_pgm_09.js
@@ -1,20 +1,34 @@
// Concatenating string properties
+var book1;
var book1;
var book2;
book1 = {
title: "The Hobbit",
- author: "J. R. R. Tolkien"
+ author: "J. R. R. Tolkien",
+ year: 1937 //Add third property
};
book2 = {
title: "Northern Lights",
- author: "Philip Pullman"
+ author: "Philip Pullman",
+ year: 1902 //Add third property
+
+};
+
+console.log(book1.title + " by " + book1.author + " in " + book1.year);
+console.log(book2.title + " by " + book2.author + " in " + book2.year);
+// Adding book-3
+var book3
+book3 = {
+ title: "Let us Dream",
+ author: "Pope Francis",
+ year: 2020 //Add third property
+
};
-console.log(book1.title + " by " + book1.author);
-console.log(book2.title + " by " + book2.author);
+console.log(book3.title + " by " + book3.author + " in " + book3.year);
diff --git a/03_JS_Objects/Ch3_pgm_10.js b/03_JS_Objects/Ch3_pgm_10.js
index 5063226..25aeb9b 100644
--- a/03_JS_Objects/Ch3_pgm_10.js
+++ b/03_JS_Objects/Ch3_pgm_10.js
@@ -12,6 +12,16 @@ player1.attempted = 1;
player1.correct = 1;
player1.score = 50;
+console.log(player1);
+
+// Updated the values
+player1.attempted = 2;
+player1.correct = 3;
+player1.score = 100;
+player1.name = "Well";
+
+console.log(player1);
+
/* Further Adventures
diff --git a/03_JS_Objects/Ch3_pgm_11.js b/03_JS_Objects/Ch3_pgm_11.js
index 44bde79..730f6bc 100644
--- a/03_JS_Objects/Ch3_pgm_11.js
+++ b/03_JS_Objects/Ch3_pgm_11.js
@@ -14,6 +14,27 @@ player1.score = player1.score + 50;
console.log(player1.name + " has scored " + player1.score);
+// increasing player1 score to 10%
+let increaseAmount = player1.score * 0.1;
+player1.score += increaseAmount;
+player1.score = Math.round(player1.score);
+console.log(player1.name + " has scored " + player1.score);
+
+// Adding player2
+var player2;
+
+player2 = {
+ name: "Well",
+ score: 60
+};
+
+console.log(player2.name + " has scored " + player2.score);
+
+// Sum of players score
+let score = player1.score + player2.score;
+console.log(player1.name + " and " + player2.name + " scored totally " + score + " scores");
+
+
/* Further Adventures
*
diff --git a/03_JS_Objects/Ch3_pgm_12.js b/03_JS_Objects/Ch3_pgm_12.js
index f3ab868..e9ed3e7 100644
--- a/03_JS_Objects/Ch3_pgm_12.js
+++ b/03_JS_Objects/Ch3_pgm_12.js
@@ -7,7 +7,16 @@ var post = {
created : "2015-06-21",
body : "You will not believe where I just woke up!! Only on a comet..."
};
-
+console.log(post.id + " The book " + post.title + " written by " + post.author + " was crerated on " + post.created);
+// Post-2
+var post2 = {
+ id : 2,
+ title : "As Good As My Word",
+ author : "KM Chandrashekhar",
+ created : "2020-05-20",
+ body : "You will not believe where I just woke up!! Only on a comet..."
+};
+console.log(post2.id + " The book " + post2.title + " written by " + post2.author + " was crerated on " + post2.created);
/* Further Adventures
diff --git a/03_JS_Objects/Ch3_pgm_13.js b/03_JS_Objects/Ch3_pgm_13.js
index a7b0cfc..7d813ac 100644
--- a/03_JS_Objects/Ch3_pgm_13.js
+++ b/03_JS_Objects/Ch3_pgm_13.js
@@ -1,14 +1,24 @@
// Location for a weather app
var location = {
- "city" : "San Francisco",
- "state" : "CA",
- "country" : "US",
- "zip" : "94101",
- "latitude" : 37.775,
- "longitude" : -122.418,
- "elevation" : 47.000
- };
+ "city" : "San Francisco",
+ "state" : "CA",
+ "country" : "US",
+ "zip" : "94101",
+ "latitude" : 37.775,
+ "longitude" : -122.418,
+ "elevation" : 47.000
+};
+// Changing the variable name
+var geolocation = {
+ "city" : "San Francisco",
+ "state" : "CA",
+ "country" : "US",
+ "zip" : "94101",
+ "latitude" : 37.775,
+ "longitude" : -122.418,
+ "elevation" : 47.000
+};
diff --git a/03_JS_Objects/Ch3_pgm_14.js b/03_JS_Objects/Ch3_pgm_14.js
index 8d8d0b4..547e54b 100644
--- a/03_JS_Objects/Ch3_pgm_14.js
+++ b/03_JS_Objects/Ch3_pgm_14.js
@@ -9,6 +9,13 @@ var questionAndAnswer = {
correctAnswer: "Paris",
marksForQuestion: 2
};
+console.log(questionAndAnswer.question);
+console.log("1 " + questionAndAnswer.answer1);
+console.log("2 " + questionAndAnswer.answer2);
+console.log("3 " + questionAndAnswer.answer3);
+console.log("4 " + questionAndAnswer.answer4);
+console.log("CorrectAnswer: " + questionAndAnswer.correctAnswer);
+console.log("Mark for Question: " + questionAndAnswer.marksForQuestion)
diff --git a/03_JS_Objects/Ch3_pgm_15.js b/03_JS_Objects/Ch3_pgm_15.js
index 635756e..8d61352 100644
--- a/03_JS_Objects/Ch3_pgm_15.js
+++ b/03_JS_Objects/Ch3_pgm_15.js
@@ -13,7 +13,22 @@ console.log(player.name);
console.log(player.name + " is in " + player.place);
console.log(player.name + " has health " + player.health);
console.log("Items: " + player.items);
+
+// Second player
+var player2;
+player2 = {
+ name: "Max",
+ health: 70,
+ place: "Thunder Theme Park",
+ items: "a rusty key, The Sword of Destiny, a piece of cheese"
+};
+
+console.log(player2.name);
+console.log(player2.name + " is in " + player2.place);
+console.log(player2.name + " has health " + player2.health);
+console.log("Items: " + player2.items);
+
/* Further Adventures
diff --git a/04_JS_Functions/Ch4_pgm_01.js b/04_JS_Functions/Ch4_pgm_01.js
index cce4238..4df2028 100644
--- a/04_JS_Functions/Ch4_pgm_01.js
+++ b/04_JS_Functions/Ch4_pgm_01.js
@@ -14,6 +14,36 @@ console.log("Actors: " + movie1.actors);
console.log("Directors: " + movie1.directors);
console.log("------------------------------");
+// movie-2
+var movie2 = {
+ title: "Toy Story",
+ actors: "Tom Hanks, Tim Allen",
+ directors: "John Lasseter"
+ };
+
+ console.log("Movie information for " + movie2.title);
+ console.log("------------------------------");
+ console.log("Actors: " + movie2.actors);
+ console.log("Directors: " + movie2.directors);
+ console.log("------------------------------");
+
+ // Blog post object
+ var blogPost = {
+ title: "My Blog post page",
+ author: "Anna Williams",
+ body: "This page contains description of the movie and the artists of the movie.",
+ date: "2024-07-05"
+ };
+
+ console.log("Blog Post Information");
+ console.log("------------------------------");
+ console.log("Title: " + blogPost.title);
+ console.log("Author: " + blogPost.author);
+ console.log("Body: " + blogPost.body);
+ console.log("Date: " + blogPost.date);
+ console.log("------------------------------");
+
+
/* Further Adventures
diff --git a/04_JS_Functions/Ch4_pgm_02.js b/04_JS_Functions/Ch4_pgm_02.js
index a97655d..709e48e 100644
--- a/04_JS_Functions/Ch4_pgm_02.js
+++ b/04_JS_Functions/Ch4_pgm_02.js
@@ -1,44 +1,95 @@
// Displaying information from similar objects
-var movie1;
-var movie2;
-var movie3;
-
-movie1 = {
+var movie1 = {
title: "Inside Out",
actors: "Amy Poehler, Bill Hader",
directors: "Pete Doctor, Ronaldo Del Carmen"
};
-movie2 = {
+var movie2 = {
title: "Spectre",
actors: "Daniel Craig, Christoph Waltz",
directors: "Sam Mendes"
};
-movie3 = {
+var movie3 = {
title: "Star Wars: Episode VII - The Force Awakens",
actors: "Harrison Ford, Mark Hamill, Carrie Fisher",
directors: "J.J.Abrams"
};
-console.log("Movie information for " + movie1.title);
-console.log("------------------------------");
-console.log("Actors: " + movie1.actors);
-console.log("Directors: " + movie1.directors);
-console.log("------------------------------");
-
-console.log("Movie information for " + movie2.title);
-console.log("------------------------------");
-console.log("Actors: " + movie2.actors);
-console.log("Directors: " + movie2.directors);
-console.log("------------------------------");
-
-console.log("Movie information for " + movie3.title);
-console.log("------------------------------");
-console.log("Actors: " + movie3.actors);
-console.log("Directors: " + movie3.directors);
-console.log("------------------------------");
+var movie4 = {
+ title: "The Martian",
+ actors: "Matt Damon, Jessica Chastain",
+ directors: "Ridley Scott"
+};
+
+function displayMovieInfo(movie) {
+ console.log("Movie information for " + movie.title);
+ console.log("------------------------------");
+ console.log("Actors: " + movie.actors);
+ console.log("Directors: " + movie.directors);
+ console.log("-------------------------------");
+}
+
+displayMovieInfo(movie1);
+displayMovieInfo(movie2);
+displayMovieInfo(movie3);
+displayMovieInfo(movie4);
+
+// Calendar events
+var sale1;
+var sale2;
+var sale3;
+var sale4;
+
+sale1 = {id:1, price: 140, taxRate: 15 };
+sale2 = {id:2, price: 40, taxRate: 10 };
+sale3 = {id:3, price: 120, taxRate: 20 };
+sale4 = {id:4, price:100, taxRate:15};
+
+sale1.tax = sale1.price * sale1.taxRate / 100;
+sale2.tax = sale2.price * sale2.taxRate / 100;
+sale3.tax = sale3.price * sale3.taxRate / 100;
+sale4.tax = sale4.price * sale4.taxRate / 100;
+
+sale1.total = sale1.price + sale1.tax;
+sale2.total = sale2.price + sale2.tax;
+sale3.total = sale3.price + sale3.tax;
+sale4.total = sale4.price + sale4.tax;
+
+
+console.log("price = $" + sale1.price);
+console.log("tax @ " + sale1.taxRate + "% = $" + sale1.tax);
+console.log("total cost = $" + sale1.total);
+
+console.log("price = $" + sale2.price);
+console.log("tax @ " + sale2.taxRate + "% = $" + sale2.tax);
+console.log("total cost = $" + sale2.total);
+
+console.log("price = $" + sale3.price);
+console.log("tax @ " + sale3.taxRate + "% = $" + sale3.tax);
+console.log("total cost = $" + sale3.total);
+
+console.log("price = $" + sale4.price);
+console.log("tax @ " + sale3.taxRate + "% = $" + sale4.tax);
+console.log("total cost = $" + sale4.total);
+
+function saleInfo(sale){
+ console.log("Sale Information: " + sale.id);
+ console.log("------------------------");
+ console.log("Price: " + sale.price);
+ console.log("Tax Rate: " + sale.taxRate);
+ console.log("Tax: " + sale.tax);
+ console.log("Total cost: " + sale.total)
+ console.log("-----------------------")
+}
+saleInfo(sale1);
+saleInfo(sale2);
+saleInfo(sale3);
+saleInfo(sale4);
+
+
diff --git a/04_JS_Functions/Ch4_pgm_03.js b/04_JS_Functions/Ch4_pgm_03.js
index 98e83bf..635a38c 100644
--- a/04_JS_Functions/Ch4_pgm_03.js
+++ b/04_JS_Functions/Ch4_pgm_03.js
@@ -3,18 +3,23 @@
var sale1;
var sale2;
var sale3;
+var sale4;
-sale1 = { price: 140, taxRate: 15 };
-sale2 = { price: 40, taxRate: 10 };
-sale3 = { price: 120, taxRate: 20 };
+sale1 = {id:1, price: 140, taxRate: 15 };
+sale2 = {id:2, price: 40, taxRate: 10 };
+sale3 = {id:3, price: 120, taxRate: 20 };
+sale4 = {id:4, price:100, taxRate:15};
sale1.tax = sale1.price * sale1.taxRate / 100;
sale2.tax = sale2.price * sale2.taxRate / 100;
sale3.tax = sale3.price * sale3.taxRate / 100;
+sale4.tax = sale4.price * sale4.taxRate / 100;
sale1.total = sale1.price + sale1.tax;
sale2.total = sale2.price + sale2.tax;
sale3.total = sale3.price + sale3.tax;
+sale4.total = sale4.price + sale4.tax;
+
console.log("price = $" + sale1.price);
console.log("tax @ " + sale1.taxRate + "% = $" + sale1.tax);
@@ -28,6 +33,24 @@ console.log("price = $" + sale3.price);
console.log("tax @ " + sale3.taxRate + "% = $" + sale3.tax);
console.log("total cost = $" + sale3.total);
+console.log("price = $" + sale4.price);
+console.log("tax @ " + sale3.taxRate + "% = $" + sale4.tax);
+console.log("total cost = $" + sale4.total);
+
+function saleInfo(sale){
+ console.log("Sale Information: " + sale.id);
+ console.log("------------------------");
+ console.log("Price: " + sale.price);
+ console.log("Tax Rate: " + sale.taxRate);
+ console.log("Tax: " + sale.tax);
+ console.log("Total cost: " + sale.total)
+ console.log("-----------------------")
+}
+saleInfo(sale1);
+saleInfo(sale2);
+saleInfo(sale3);
+saleInfo(sale4);
+
diff --git a/04_JS_Functions/Ch4_pgm_04.js b/04_JS_Functions/Ch4_pgm_04.js
index e94a57f..e58d92e 100644
--- a/04_JS_Functions/Ch4_pgm_04.js
+++ b/04_JS_Functions/Ch4_pgm_04.js
@@ -6,6 +6,8 @@ sayHello = function () {
console.log("Hello World!");
};
+sayHello()
+
/* Further Adventures
diff --git a/04_JS_Functions/Ch4_pgm_05.js b/04_JS_Functions/Ch4_pgm_05.js
index d6d1a29..88cb494 100644
--- a/04_JS_Functions/Ch4_pgm_05.js
+++ b/04_JS_Functions/Ch4_pgm_05.js
@@ -3,9 +3,16 @@
var findTotal;
var displayMenu;
+//Declaring variables
+var number1 = 45;
+var number2 = 90;
+var result;
+
findTotal = function () {
result = number1 + number2;
};
+findTotal(); //Running the function
+console.log(result); //log findTotal function
displayMenu = function () {
console.log("Please choose an option:");
@@ -13,6 +20,7 @@ displayMenu = function () {
console.log("(2) Upload file");
console.log("(9) Quit");
};
+displayMenu();
diff --git a/04_JS_Functions/Ch4_pgm_06.js b/04_JS_Functions/Ch4_pgm_06.js
index 02ea402..daad2e5 100644
--- a/04_JS_Functions/Ch4_pgm_06.js
+++ b/04_JS_Functions/Ch4_pgm_06.js
@@ -3,13 +3,21 @@
var sayHello;
sayHello = function () {
- console.log("Hello World!");
+ console.log("Hello\nWorld!");
};
sayHello();
sayHello();
sayHello();
+function printLetters() {
+ var message = "Hello World!";
+ for (var i = 0; i < message.length; i++) {
+ console.log(message[i]);
+ }
+}
+
+printLetters();
/* Further Adventures
diff --git a/04_JS_Functions/Ch4_pgm_07.js b/04_JS_Functions/Ch4_pgm_07.js
index e7d112e..984f2c8 100644
--- a/04_JS_Functions/Ch4_pgm_07.js
+++ b/04_JS_Functions/Ch4_pgm_07.js
@@ -1,18 +1,18 @@
// Using the findTotal function to display a calculation
-var number1 = 1000;
-var number2 = 66;
+var number1 = 1008; //Updated the value
+var number2 = 680; //Updated the value
+var number3 = 548; //assigned third variable
var result;
var findTotal;
findTotal = function () {
- result = number1 + number2;
+ result = number1 + number2 + number3;
};
findTotal();
-console.log(number1 + " + " + number2 + " = " + result);
-
+console.log(number1 + " + " + number2 + " + " + number3 + " = " + result);
/* Further Adventures
diff --git a/04_JS_Functions/Ch4_pgm_08.js b/04_JS_Functions/Ch4_pgm_08.js
index a0cb2cf..4ce90d8 100644
--- a/04_JS_Functions/Ch4_pgm_08.js
+++ b/04_JS_Functions/Ch4_pgm_08.js
@@ -3,14 +3,28 @@
var displayMenu;
displayMenu = function () {
- console.log("Please choose an option:");
- console.log("(1) Print log");
- console.log("(2) Upload file");
- console.log("(9) Quit");
+ console.log("Please choose an option:");
+ console.log("(1) Print log");
+ console.log("(2) Upload file");
+ console.log("(3) Download file");
+ console.log("(4) Delete file");
+ console.log("(9) Quit");
};
displayMenu();
+var displayMyMenu;
+
+displayMyMenu = function () {
+ console.log("Welcome to My Menu:");
+ console.log("(1) Home Page");
+ console.log("(2) Edit profile");
+ console.log("(3) Password");
+ console.log("(4) Log out");
+ console.log("(9) Exit");
+};
+
+displayMyMenu();
/* Further Adventures
diff --git a/04_JS_Functions/Ch4_pgm_09.js b/04_JS_Functions/Ch4_pgm_09.js
index 2a6c0c2..3c3dfe4 100644
--- a/04_JS_Functions/Ch4_pgm_09.js
+++ b/04_JS_Functions/Ch4_pgm_09.js
@@ -2,6 +2,12 @@
var showMovieInfo;
+var movie = {
+ title: "Spectre",
+ actors: "Daniel Craig, Christoph Waltz",
+ directors: "Sam Mendes"
+ };
+
showMovieInfo = function () {
console.log("Movie information for " + movie.title);
console.log("------------------------------");
@@ -9,7 +15,7 @@ showMovieInfo = function () {
console.log("Directors: " + movie.directors);
console.log("------------------------------");
};
-
+showMovieInfo();
/* Further Adventures
diff --git a/04_JS_Functions/Ch4_pgm_10.js b/04_JS_Functions/Ch4_pgm_10.js
index fcb029c..37cd370 100644
--- a/04_JS_Functions/Ch4_pgm_10.js
+++ b/04_JS_Functions/Ch4_pgm_10.js
@@ -10,6 +10,14 @@ movie1 = {
directors: "Pete Doctor, Ronaldo Del Carmen"
};
+var movie2 = {
+ title: "Spectre",
+ actors: "Daniel Craig, Christoph Waltz",
+ directors: "Sam Mendes"
+
+};
+
+
showMovieInfo = function () {
console.log("Movie information for " + movie.title);
console.log("------------------------------");
@@ -19,9 +27,12 @@ showMovieInfo = function () {
};
movie = movie1;
+movie = movie2;
showMovieInfo();
+//After assigning values for movie 2 values it shows the values of movie 2 values in the showMovieInfo() function
+
/* Further Adventures
diff --git a/04_JS_Functions/Ch4_pgm_11.js b/04_JS_Functions/Ch4_pgm_11.js
index d53257d..446d801 100644
--- a/04_JS_Functions/Ch4_pgm_11.js
+++ b/04_JS_Functions/Ch4_pgm_11.js
@@ -1,5 +1,3 @@
-// Using the same function with multiple objects
-
var movie1;
var movie2;
var movie3;
@@ -41,6 +39,52 @@ showMovieInfo();
movie = movie3;
showMovieInfo();
+//creating quizQuestion function
+var quizQuestion1;
+var quizQuestion2;
+var quizQuestion3;
+var quizInfo;
+
+quizQuestion1 = {
+ id: 1,
+ question: "who is the father of nation?",
+ option1: "Gandhiji",
+ option2: "Nehru",
+ correctAnswer: "Gandhiji"
+};
+quizQuestion2 = {
+ id: 2,
+ question: "when did India got independence?",
+ option1: 1947,
+ option2: 1956,
+ correctAnswer: 1947
+};
+quizQuestion3 = {
+ id: 3,
+ question: "who is the father of computer?",
+ option1: "Charles Babbage",
+ option2: "Musk Alon",
+ correctAnswer: "Charles Babbage"
+};
+
+quizInfo = function (){
+ console.log("Question: " + quizQuestion.id);
+ console.log("--------------------");
+ console.log(quizQuestion.id + quizQuestion.question);
+ console.log("option-1 " + quizQuestion.option);
+ console.log("option-2 " + quizQuestion.option);
+ console.log("correct answer: " + quizQuestion.correctAnswer);
+}
+
+quizQuestion = quizQuestion1;
+quizInfo();
+
+quizQuestion = quizQuestion2;
+quizInfo();
+
+quizQuestion = quizQuestion3;
+quizInfo();
+
/* Further Adventures
diff --git a/04_JS_Functions/Ch4_pgm_12.js b/04_JS_Functions/Ch4_pgm_12.js
index 8c0eb6d..750b818 100644
--- a/04_JS_Functions/Ch4_pgm_12.js
+++ b/04_JS_Functions/Ch4_pgm_12.js
@@ -1,54 +1,34 @@
-// Using functions to add and display tax
-
var sale1;
-var sale2;
-var sale3;
-var sale;
+var sale2;
+var sale3;
+var sale4;
var calculateTax;
-var displaySale;
+var displaySale;
+var processSale;
sale1 = { price: 140, taxRate: 15 };
sale2 = { price: 40, taxRate: 10 };
sale3 = { price: 120, taxRate: 20 };
+sale4 = { price: 200, taxRate: 5 };
-calculateTax = function () {
- sale.tax = sale.price * sale.taxRate / 100;
- sale.total = sale.price + sale.tax;
+calculateTax = function (sale) {
+ sale.tax = sale.price * sale.taxRate / 100;
+ sale.total = sale.price + sale.tax;
};
-displaySale = function () {
+displaySale = function (sale) {
console.log("price = $" + sale.price);
- console.log("tax @ " + sale.taxRate + "% = $" + sale.tax);
- console.log("total cost = $" + sale.total);
+ console.log("tax @ " + sale.taxRate + "% = $" + sale.tax.toFixed(2));
+ console.log("total cost = $" + sale.total.toFixed(2));
+ console.log("--------------------------");
};
-sale = sale1;
-calculateTax();
-displaySale();
-
-sale = sale2;
-calculateTax();
-displaySale();
-
-sale = sale3;
-calculateTax();
-displaySale();
-
-
+processSale = function (sale) {
+ calculateTax(sale);
+ displaySale(sale);
+};
-/* Further Adventures
- *
- * 1) Add a fourth sale object.
- *
- * 2) Update the code so that tax is calculated
- * and the new sale is displayed.
- *
- * Having two separate functions to calculate tax
- * and display sales is good, each has a specific purpose.
- * Having to call both functions
- * for each sale object is not so good.
- *
- * 3) Can you change the code so that you don't
- * have to call both functions for every sale?
- *
- */
\ No newline at end of file
+processSale(sale1);
+processSale(sale2);
+processSale(sale3);
+processSale(sale4);
\ No newline at end of file
diff --git a/04_JS_Functions/Ch4_pgm_13.js b/04_JS_Functions/Ch4_pgm_13.js
index a8d6230..ce2aaf9 100644
--- a/04_JS_Functions/Ch4_pgm_13.js
+++ b/04_JS_Functions/Ch4_pgm_13.js
@@ -1,5 +1,3 @@
-// A function to display player information
-
var player1;
var player2;
var player;
@@ -17,11 +15,19 @@ player2 = {
health: 40
};
+showPlayerLocation = function (player) {
+ console.log(player.name + " is in " + player.place);
+};
+
+showPlayerHealth = function (player) {
+ console.log(player.name + " has health " + player.health);
+};
+
showPlayerInfo = function () {
console.log(player.name);
console.log("------------------------------");
- console.log(player.name + " is in " + player.place);
- console.log(player.name + " has health " + player.health);
+ showPlayerLocation(player);
+ showPlayerHealth(player);
console.log("------------------------------");
console.log("");
};
@@ -30,19 +36,4 @@ player = player1;
showPlayerInfo();
player = player2;
-showPlayerInfo();
-
-
-
-/* Further Adventures
- *
- * 1) Write a function that just shows
- * where the player is.
- *
- * 2) Write a function that just shows
- * the player's health.
- *
- * 3) Change the showPlayerInfo function
- * to use your two functions.
- *
- */
\ No newline at end of file
+showPlayerInfo();
\ No newline at end of file
diff --git a/05_JS_Arguments/Ch5_pgm_01.js b/05_JS_Arguments/Ch5_pgm_01.js
index 40e3b42..7ed389b 100644
--- a/05_JS_Arguments/Ch5_pgm_01.js
+++ b/05_JS_Arguments/Ch5_pgm_01.js
@@ -6,7 +6,7 @@ var showMessage;
message = "It's full of stars!";
showMessage = function () {
- console.log(message);
+ console.log(messageeeee);
};
showMessage();
diff --git a/05_JS_Arguments/Ch5_pgm_02.js b/05_JS_Arguments/Ch5_pgm_02.js
index 7c7c175..e361ebf 100644
--- a/05_JS_Arguments/Ch5_pgm_02.js
+++ b/05_JS_Arguments/Ch5_pgm_02.js
@@ -1,12 +1,19 @@
// Breaking a function by changing a variable name
var msg;
+var msg2;
+var msg3;
var showMessage;
msg = "It's full of stars!";
+msg2 = "And there is a beautiful moon"
+msg3 = msg.concat(msg2);
showMessage = function () {
- console.log(message);
+ // console.log(message);
+ console.log(msg); //updated to as it works
+ console.log(msg2);
+ console.log(msg3);
};
showMessage();
diff --git a/05_JS_Arguments/Ch5_pgm_03.js b/05_JS_Arguments/Ch5_pgm_03.js
index 12318b7..ac030b4 100644
--- a/05_JS_Arguments/Ch5_pgm_03.js
+++ b/05_JS_Arguments/Ch5_pgm_03.js
@@ -1,29 +1,14 @@
-// Passing information to a function
-
var showMessage;
showMessage = function (message) {
- console.log("The message is: " + message);
+ console.log("The message is: ");
+ console.log(message);
};
showMessage("It's full of stars!");
+showMessage("Hello to Jason Isaacs");
+showMessage("Hello to Jason Isaacs and Stephen Fry");
-
-
-/* Further Adventures
- *
- * 1) Change the message in the parentheses
- * when showMessage is called on line 9.
- *
- * The value in the parentheses when showMessage is called
- * is an argument. "It's full of stars!" was the
- * original argument on line 9.
- *
- * 2) Add two more calls to the showMessage function
- * with different arguments each time.
- *
- * 3) Change the showMessage function itself.
- * Make it add some extra text after the
- * message passed in.
- *
- */
\ No newline at end of file
+var myMessage;
+myMessage = "Thank You!";
+showMessage(myMessage);
\ No newline at end of file
diff --git a/05_JS_Arguments/Ch5_pgm_04.js b/05_JS_Arguments/Ch5_pgm_04.js
index 01552f3..ac030b4 100644
--- a/05_JS_Arguments/Ch5_pgm_04.js
+++ b/05_JS_Arguments/Ch5_pgm_04.js
@@ -1,27 +1,14 @@
-// Calling the same function with different arguments
-
var showMessage;
showMessage = function (message) {
- console.log("The message is: " + message);
+ console.log("The message is: ");
+ console.log(message);
};
showMessage("It's full of stars!");
showMessage("Hello to Jason Isaacs");
showMessage("Hello to Jason Isaacs and Stephen Fry");
-
-
-/* Further Adventures
- *
- * 1) Change the showMessage function to
- * display its prefixed text on a
- * separate line to the message.
- *
- * 2) Declare a myMessage variable and
- * assign it a string value.
- *
- * 3) Call the showMessage function with
- * myMessage as the argument.
- *
- */
\ No newline at end of file
+var myMessage;
+myMessage = "Thank You!";
+showMessage(myMessage);
\ No newline at end of file
diff --git a/05_JS_Arguments/Ch5_pgm_05.js b/05_JS_Arguments/Ch5_pgm_05.js
index 2e88dc9..741dfae 100644
--- a/05_JS_Arguments/Ch5_pgm_05.js
+++ b/05_JS_Arguments/Ch5_pgm_05.js
@@ -1,5 +1,3 @@
-// Using the square function
-
var square;
square = function (numberToSquare) {
@@ -13,23 +11,23 @@ square(-2);
square(1111);
square(0.5);
+var cube;
+cube = function(numberToCube){
+ var cube = Math.pow(numberToCube, 3);
+ console.log("The cube of " +numberToCube + " is: " + cube);
+}
+cube(4);
+cube(5);
+cube(99);
+cube(10);
+var squareRoot;
+squareRoot = function(numberToSqrt){
+ var squareRoot = Math.sqrt(numberToSqrt);
+ console.log("The Square Root of " + numberToSqrt + " is: " + squareRoot);
+}
+squareRoot(4);
+squareRoot(81);
+squareRoot(25);
+squareRoot(1000);
-/* Further Adventures
- *
- * 1) Define a cube function that cubes
- * any number passed in as an argument.
- *
- * 2) Call your cube function four times
- * with different arguments to test it.
- *
- * Math.sqrt is a built-in function to find
- * the square root of a number.
- * e.g. Math.sqrt(9) finds the square root of 9.
- *
- * 3) Define and test a squareRoot function
- * to find square roots and display
- * them on the console.
- * e.g. The square root of 9 is 3.
- *
- */
\ No newline at end of file
diff --git a/05_JS_Arguments/Ch5_pgm_06.js b/05_JS_Arguments/Ch5_pgm_06.js
index a3db63d..2476013 100644
--- a/05_JS_Arguments/Ch5_pgm_06.js
+++ b/05_JS_Arguments/Ch5_pgm_06.js
@@ -6,9 +6,39 @@ showSum = function (number1, number2) {
var total = number1 + number2;
console.log("The sum is " + total);
};
-
showSum(30, 23);
showSum(2.8, -5);
+showSum(56, 74);
+
+
+var showProduct;
+showProduct = function(number1, number2){
+ var product = number1 * number2;
+ console.log("The product is: " + product);
+}
+showProduct(3, 3);
+showProduct(99, 81);
+showProduct(43, 78);
+
+
+var showDifference;
+showDifference = function(number1, number2){
+ var difference = number1 - number2;
+ console.log("The difference is: " + difference);
+}
+showDifference(45, 60);
+showDifference(9.9, 3.56);
+showDifference(0, 45);
+
+
+var showQuotient;
+showQuotient = function(number1, number2){
+ var quotient = number1 / number2;
+ console.log("The quotient is: " + quotient);
+}
+showQuotient(9, 7);
+showQuotient(9,3);
+showQuotient(7,8);
diff --git a/05_JS_Arguments/Ch5_pgm_07.js b/05_JS_Arguments/Ch5_pgm_07.js
index 1fd12f9..9c68c1b 100644
--- a/05_JS_Arguments/Ch5_pgm_07.js
+++ b/05_JS_Arguments/Ch5_pgm_07.js
@@ -3,13 +3,21 @@
var showPlayerName;
showPlayerName = function (playerName) {
- console.log(playerName);
+ // console.log(playerName);
+ console.log("The player's name is " + playerName);
};
showPlayerName("Kandra");
showPlayerName("Dax");
+var playerNameLength;
+playerNameLength = function(playerName){
+ console.log("The number of letters in the: " + playerName.length);
+}
+playerNameLength("Kandra");
+playerNameLength("KGCAS");
+
/* Further Adventures
*
diff --git a/05_JS_Arguments/Ch5_pgm_08.js b/05_JS_Arguments/Ch5_pgm_08.js
index 1f4dfcb..863afb4 100644
--- a/05_JS_Arguments/Ch5_pgm_08.js
+++ b/05_JS_Arguments/Ch5_pgm_08.js
@@ -5,7 +5,8 @@ var player2;
var showPlayerName;
showPlayerName = function (playerName) {
- console.log(playerName);
+ console.log(playerName.toUpperCase());
+ console.log(playerName.toLowerCase());
};
player1 = {
diff --git a/05_JS_Arguments/Ch5_pgm_09.js b/05_JS_Arguments/Ch5_pgm_09.js
index d500a81..5033fe4 100644
--- a/05_JS_Arguments/Ch5_pgm_09.js
+++ b/05_JS_Arguments/Ch5_pgm_09.js
@@ -2,14 +2,15 @@
var showPlayerHealth;
-showPlayerHealth = function (playerName, playerHealth) {
- console.log(playerName + " has health " + playerHealth);
-};
+showPlayerHealth = function(playerName, playerHealth){
+ var healthInfo;
+ healthInfo = playerName + ": health " + playerHealth;
+ console.log(healthInfo);
+}
showPlayerHealth("Kandra", 50);
showPlayerHealth("Dax", 40);
-
-
+showPlayerHealth("Maxwell", 80);
/* Further Adventures
*
diff --git a/05_JS_Arguments/Ch5_pgm_10.js b/05_JS_Arguments/Ch5_pgm_10.js
index cac70cc..8fe56f2 100644
--- a/05_JS_Arguments/Ch5_pgm_10.js
+++ b/05_JS_Arguments/Ch5_pgm_10.js
@@ -4,24 +4,27 @@ var player1;
var player2;
var showPlayerHealth;
-showPlayerHealth = function (playerName, playerHealth) {
- console.log(playerName + " has health " + playerHealth);
+showPlayerHealth = function (playerName, playerHealth,playerHealthMultiplier) {
+ var playerHealthMultiplier = playerHealth * playerHealthMultiplier;
+ console.log(playerName + " has health " + playerHealthMultiplier);
};
player1 = {
name: "Kandra",
place: "The Dungeon of Doom",
- health: 50
+ health: 50,
+ healthMultiplier: 10
};
player2 = {
name: "Dax",
place: "The Old Library",
- health: 40
+ health: 40,
+ healthMultiplier: 15
};
-showPlayerHealth(player1.name, player1.health);
-showPlayerHealth(player2.name, player2.health);
+showPlayerHealth(player1.name, player1.health, player1.healthMultiplier);
+showPlayerHealth(player2.name, player2.health, player2.healthMultiplier);
diff --git a/05_JS_Arguments/Ch5_pgm_11.js b/05_JS_Arguments/Ch5_pgm_11.js
index d6ea18b..320798e 100644
--- a/05_JS_Arguments/Ch5_pgm_11.js
+++ b/05_JS_Arguments/Ch5_pgm_11.js
@@ -3,11 +3,13 @@
var showPlayerPlace;
showPlayerPlace = function (playerName, playerPlace) {
- console.log(playerName + " is in " + playerPlace);
+ console.log(playerName[0] + " is in " + playerPlace);//display in array format.
+ console.log(playerName[1] + " is in " + playerPlace);//display the second letter of the name.
+ console.log(playerName[3] + " is in " + playerPlace);//display the fourth letter of the name because it the number represents the index of array.
};
showPlayerPlace("Kandra", "The Dungeon of Doom");
-showPlayerPlace("Dax", "The Old Library");
+showPlayerPlace("Dax", "The Old Library")
diff --git a/05_JS_Arguments/Ch5_pgm_12.js b/05_JS_Arguments/Ch5_pgm_12.js
index f6376ad..fb6d892 100644
--- a/05_JS_Arguments/Ch5_pgm_12.js
+++ b/05_JS_Arguments/Ch5_pgm_12.js
@@ -5,7 +5,14 @@ var player2;
var showPlayerPlace;
showPlayerPlace = function (playerName, playerPlace) {
- console.log(playerName + " is in " + playerPlace);
+ console.log(playerName.substring(0,1) + " is in " + playerPlace);
+ console.log(playerName.substring(0,2) + " is in " + playerPlace);
+ console.log(playerName.substring(0,3) + " is in " + playerPlace);
+ console.log(playerName.substring(1,2) + " is in " + playerPlace);
+ console.log(playerName.substring(1,3) + " is in " + playerPlace);
+
+ //The substring method shows in the array method that is if we take (0,2)
+ //it takes the letters from 0 to 2 but not 2.
};
player1 = {
diff --git a/05_JS_Arguments/Ch5_pgm_13.js b/05_JS_Arguments/Ch5_pgm_13.js
index 82efdcc..64ccd2a 100644
--- a/05_JS_Arguments/Ch5_pgm_13.js
+++ b/05_JS_Arguments/Ch5_pgm_13.js
@@ -4,6 +4,8 @@ var showPlayerInfo;
var showPlayerName;
var showPlayerHealth;
var showPlayerPlace;
+var showBlankLine;
+var showLine;
showPlayerName = function (playerName) {
console.log(playerName);
@@ -17,22 +19,31 @@ showPlayerPlace = function (playerName, playerPlace) {
console.log(playerName + " is in " + playerPlace);
};
+showLine = function(){
+ console.log("---------------------------------")
+}
+
+showBlankLine = function(){
+ console.log("");
+}
+
showPlayerInfo = function (playerName, playerPlace, playerHealth) {
console.log("");
showPlayerName(playerName);
- console.log("----------------------------");
+ showLine();
showPlayerPlace(playerName, playerPlace);
showPlayerHealth(playerName, playerHealth);
- console.log("----------------------------");
- console.log("");
+ showLine();
+ showBlankLine();
};
showPlayerInfo("Kandra", "The Dungeon of Doom", 50);
showPlayerInfo("Dax", "The Old Library", 40);
+s
diff --git a/05_JS_Arguments/Ch5_pgm_14.js b/05_JS_Arguments/Ch5_pgm_14.js
index ec0a863..2cd5fab 100644
--- a/05_JS_Arguments/Ch5_pgm_14.js
+++ b/05_JS_Arguments/Ch5_pgm_14.js
@@ -1,7 +1,17 @@
// Displaying a player's information using properties
+var showLine = function (length) {
+ var line = "******************************"; // a long string of asterisks
+ console.log(line.substring(0, length));
+};
+
var showPlayerName = function (playerName) {
- console.log(playerName);
+ var nameLength = playerName.length;
+ var boxWidth = nameLength + 4; // Adding 4 for the spaces and the border
+
+ showLine(boxWidth);
+ console.log("* " + playerName + " *");
+ showLine(boxWidth);
};
var showPlayerHealth = function (playerName, playerHealth) {
@@ -17,12 +27,12 @@ var showPlayerInfo = function (playerName, playerPlace, playerHealth) {
showPlayerName(playerName);
- console.log("----------------------------");
+ showLine(28); // A line for separation
showPlayerPlace(playerName, playerPlace);
showPlayerHealth(playerName, playerHealth);
- console.log("----------------------------");
+ showLine(28); // A line for separation
console.log("");
};
@@ -42,8 +52,6 @@ showPlayerInfo(player1.name, player1.place, player1.health);
showPlayerInfo(player2.name, player2.place, player2.health);
-
-
/* Further Adventures
*
* 1) Define a showLine function with a parameter
diff --git a/06_JS_Return_values/Ch6_pgm_01.js b/06_JS_Return_values/Ch6_pgm_01.js
index c4caf2e..f40027a 100644
--- a/06_JS_Return_values/Ch6_pgm_01.js
+++ b/06_JS_Return_values/Ch6_pgm_01.js
@@ -4,7 +4,7 @@ var getMessage;
var response;
getMessage = function () {
- return "I’m going on an adventure!";
+ return "Hello, Have a great a day!";
};
response = getMessage();
@@ -12,7 +12,6 @@ response = getMessage();
console.log(response);
-
/* Further Adventures
*
* 1) Write a getMyMessage function
diff --git a/06_JS_Return_values/Ch6_pgm_02.js b/06_JS_Return_values/Ch6_pgm_02.js
index 72e140c..94b013a 100644
--- a/06_JS_Return_values/Ch6_pgm_02.js
+++ b/06_JS_Return_values/Ch6_pgm_02.js
@@ -2,12 +2,14 @@
var getHelloTo;
var fullMessage;
+var name1 = "Kandra";
+var name2 = "Dax";
-getHelloTo = function (name) {
- return "Hello to " + name;
+getHelloTo = function (name1, name2) {
+ return "Hello to " + name1 + " and " + name2;
};
-fullMessage = getHelloTo("Kandra");
+fullMessage = getHelloTo(name1, name2);
console.log(fullMessage);
diff --git a/06_JS_Return_values/Ch6_pgm_03.js b/06_JS_Return_values/Ch6_pgm_03.js
index 5376bce..b029c51 100644
--- a/06_JS_Return_values/Ch6_pgm_03.js
+++ b/06_JS_Return_values/Ch6_pgm_03.js
@@ -4,10 +4,13 @@ var getHelloTo;
getHelloTo = function (name) {
return "Hello to " + name;
+ var template = "Hello to {{name}}";
+ template = template.replace("{{name}}", Daniel);
+ return template; //No it does not work.
};
console.log(getHelloTo("Kandra"));
-console.log(getHelloTo("Dax"));
+console.log(getHelloTo("Dax"));
diff --git a/06_JS_Return_values/Ch6_pgm_04.js b/06_JS_Return_values/Ch6_pgm_04.js
index 5514ffc..57cb808 100644
--- a/06_JS_Return_values/Ch6_pgm_04.js
+++ b/06_JS_Return_values/Ch6_pgm_04.js
@@ -2,15 +2,14 @@
var add;
-add = function (number1, number2) {
- var total = number1 + number2;
+add = function (number1, number2, number3) {
+ var total = number1 + number2 + number3;
return total;
};
var sum = add(50, 23);
-
-console.log(sum);
+console.log(sum = add(45, 90, 100));
diff --git a/06_JS_Return_values/Ch6_pgm_05.js b/06_JS_Return_values/Ch6_pgm_05.js
index b6f6258..08bfd22 100644
--- a/06_JS_Return_values/Ch6_pgm_05.js
+++ b/06_JS_Return_values/Ch6_pgm_05.js
@@ -2,11 +2,16 @@
var totalCost;
-totalCost = function (callOutCharge, costPerHour, numberOfHours) {
- return callOutCharge + costPerHour * numberOfHours;
+totalCost = function (callOutCharge, costPerHour, numberOfHours, discount) {
+ return callOutCharge + costPerHour * numberOfHours - discount;
};
-console.log("$" + totalCost(30, 40, 3));
+// Cost for 12 hours of work
+var costFor12Hours = totalCost(30, 40, 12, 0);
+console.log("Cost for 12 hours: $" + costFor12Hours);
+
+// Total cost for 3 hours with a $20 discount
+console.log("$" + totalCost(30, 40, 3, 20));
diff --git a/06_JS_Return_values/Ch6_pgm_06.js b/06_JS_Return_values/Ch6_pgm_06.js
index 42d82ea..40be62d 100644
--- a/06_JS_Return_values/Ch6_pgm_06.js
+++ b/06_JS_Return_values/Ch6_pgm_06.js
@@ -21,6 +21,11 @@ totalCost = function (callOutCharge, costPerHour, numberOfHours) {
return callOutCharge + costPerHour * numberOfHours;
};
+// it run the function in the console and we get the correct output
+//getHelloTo("Arwen");
+//sum(5, 10);
+//totalCost(30, 40, 3);
+
/* Further Adventures
diff --git a/06_JS_Return_values/Ch6_pgm_07.js b/06_JS_Return_values/Ch6_pgm_07.js
index e16e09e..b2f649c 100644
--- a/06_JS_Return_values/Ch6_pgm_07.js
+++ b/06_JS_Return_values/Ch6_pgm_07.js
@@ -1,12 +1,15 @@
// Getting a string for a player’s name
-var getPlayerName;
-
-getPlayerName = function (playerName) {
- return playerName;
+var getPlayerName = function (playerName) {
+ var prefixSuffix = "====";
+ var border = "|";
+ return prefixSuffix + " " + playerName + " " + prefixSuffix + "\n" + border + "\n" + border + " " + playerName + "\n" + border;
};
-console.log(getPlayerName("Kandra"));
+console.log(getPlayerName("Kandra"));
+console.log(getPlayerName("Kiki"));
+console.log(getPlayerName("Mahesha"));
+console.log(getPlayerName("Jahver"));
diff --git a/06_JS_Return_values/Ch6_pgm_08.js b/06_JS_Return_values/Ch6_pgm_08.js
index e873827..39ac0ce 100644
--- a/06_JS_Return_values/Ch6_pgm_08.js
+++ b/06_JS_Return_values/Ch6_pgm_08.js
@@ -2,6 +2,7 @@
var getPlayerHealth;
var getPlayerPlace;
+var showPlayerInfo;
getPlayerHealth = function (playerName, playerHealth) {
return playerName + " has health " + playerHealth;
@@ -11,8 +12,17 @@ getPlayerPlace = function (playerName, playerPlace) {
return playerName + " is in " + playerPlace;
};
+showPlayerInfo = function (playerName, playerHealth, playerPlace) {
+ console.log(getPlayerHealth(playerName, playerHealth));
+ console.log(getPlayerPlace(playerName, playerPlace));
+};
+
+// Testing the functions
console.log(getPlayerHealth("Kandra", 50));
console.log(getPlayerPlace("Kandra", "The Dungeon of Doom"));
+console.log("");
+
+showPlayerInfo("Dax", 50, "The Bath");
diff --git a/06_JS_Return_values/Ch6_pgm_09.js b/06_JS_Return_values/Ch6_pgm_09.js
index c744b8c..ce6af05 100644
--- a/06_JS_Return_values/Ch6_pgm_09.js
+++ b/06_JS_Return_values/Ch6_pgm_09.js
@@ -36,8 +36,8 @@ getPlayerInfo = function (playerName, playerPlace, playerHealth) {
};
console.log(getPlayerInfo("Kandra", "The Dungeon of Doom", 50));
-
-
+console.log(getPlayerInfo("Daniel", "The Bath", 40));
+//in console if we call getPlayerInfo() without arguments then it returns undefined.
/* Further Adventures
diff --git a/06_JS_Return_values/Ch6_pgm_10.js b/06_JS_Return_values/Ch6_pgm_10.js
index fdfb48c..d4584ce 100644
--- a/06_JS_Return_values/Ch6_pgm_10.js
+++ b/06_JS_Return_values/Ch6_pgm_10.js
@@ -1,5 +1,4 @@
// Displaying player information using objects
-
var getPlayerName = function (playerName) {
return playerName;
};
@@ -16,13 +15,18 @@ var getBorder = function () {
return "================================";
};
-var getPlayerInfo = function (playerName, playerPlace, playerHealth) {
+var getPlayerItems = function (playerName, playerItems) {
+ return playerName + " has the following items: " + playerItems;
+};
+
+var getPlayerInfo = function (playerName, playerPlace, playerHealth, playerItems) {
var playerInfo;
playerInfo = "\n" + getPlayerName(playerName);
playerInfo += "\n" + getBorder();
playerInfo += "\n" + getPlayerPlace(playerName, playerPlace);
playerInfo += "\n" + getPlayerHealth(playerName, playerHealth);
+ playerInfo += "\n" + getPlayerItems(playerName, playerItems);
playerInfo += "\n" + getBorder();
playerInfo += "\n";
@@ -32,18 +36,19 @@ var getPlayerInfo = function (playerName, playerPlace, playerHealth) {
var player1 = {
name: "Kandra",
place: "The Dungeon of Doom",
- health: 50
+ health: 50,
+ items: "a rusty key, a piece of cheese"
};
var player2 = {
name: "Dax",
place: "The Old Library",
- health: 40
+ health: 40,
+ items: "an ancient book, a silver coin"
};
-console.log(getPlayerInfo(player1.name, player1.place, player1.health));
-console.log(getPlayerInfo(player2.name, player2.place, player2.health));
-
+console.log(getPlayerInfo(player1.name, player1.place, player1.health, player1.items));
+console.log(getPlayerInfo(player2.name, player2.place, player2.health, player2.items));
/* Further Adventures
diff --git a/07_JS_Object_Arguments/Ch7_pgm_01.js b/07_JS_Object_Arguments/Ch7_pgm_01.js
index 83bf73b..e0d1ebb 100644
--- a/07_JS_Object_Arguments/Ch7_pgm_01.js
+++ b/07_JS_Object_Arguments/Ch7_pgm_01.js
@@ -1,6 +1,8 @@
// Passing a function an object as an argument
var planet1;
+var planet2;
+var planet3;
var getPlanetInfo;
planet1 = {
@@ -10,12 +12,29 @@ planet1 = {
radius: 69911,
sizeRank: 1
};
+planet2 = {
+ name: "Mercury",
+ position: 1,
+ type: "Heatest Planet",
+ radius: 69911,
+ sizeRank: 1
+};
+planet3 = {
+ name: "Earth",
+ position: 3,
+ type: "Living Planet",
+ radius: 69911,
+ sizeRank: 1
+};
+
getPlanetInfo = function (planet) {
- return planet.name + ": planet number " + planet.position;
+ return planet.name + ": planet number " + planet.position + " which is known as " + planet.type;
};
console.log(getPlanetInfo(planet1));
+console.log(getPlanetInfo(planet2));
+console.log(getPlanetInfo(planet3));
diff --git a/07_JS_Object_Arguments/Ch7_pgm_02.js b/07_JS_Object_Arguments/Ch7_pgm_02.js
index ec98f6b..31aea16 100644
--- a/07_JS_Object_Arguments/Ch7_pgm_02.js
+++ b/07_JS_Object_Arguments/Ch7_pgm_02.js
@@ -4,20 +4,20 @@ var planet1 = { name: "Jupiter", radius: 69911 };
var calculateSizes = function (planet) {
var r = planet.radius;
+ planet.diameter = 2 * r;
planet.area = 4 * 3.142 * r * r;
planet.volume = 4 * 3.142 * r * r * r / 3;
};
var displaySizes = function (planet) {
console.log(planet.name);
+ console.log("diameter = " + planet.diameter + " km");
console.log("surface area = " + planet.area + " square km");
console.log("volume = " + planet.volume + " cubic km");
};
calculateSizes(planet1);
-displaySizes(planet1);
-
-
+displaySizes(planet1);
/* Further Adventures
*
diff --git a/07_JS_Object_Arguments/Ch7_pgm_03.js b/07_JS_Object_Arguments/Ch7_pgm_03.js
index a0dfd2f..804ff6a 100644
--- a/07_JS_Object_Arguments/Ch7_pgm_03.js
+++ b/07_JS_Object_Arguments/Ch7_pgm_03.js
@@ -25,7 +25,30 @@ planet2 = buildPlanet("Neptune", 8, "Ice Giant", 24622, 4);
console.log(getPlanetInfo(planet1));
console.log(getPlanetInfo(planet2));
+// For cars
+var buildCar;
+var getCarInfo;
+var car1;
+var car2;
+buildCar = function (name, type, kilometer, country) {
+ return {
+ name: name,
+ type: type,
+ kilometer:kilometer,
+ country:country
+ };
+};
+
+getCarInfo = function (car) {
+ return car.name.toUpperCase() + ": car " + car.type;
+};
+
+car1 = buildCar("VolksWagon", "Taigun", 140, "USA");
+car2 = buildCar("Tata", "Harrier", 170, "India");
+
+console.log(getCarInfo(car1));
+console.log(getCarInfo(car2));
/* Further Adventures
*
diff --git a/07_JS_Object_Arguments/Ch7_pgm_04.js b/07_JS_Object_Arguments/Ch7_pgm_04.js
index 9b665fe..c363779 100644
--- a/07_JS_Object_Arguments/Ch7_pgm_04.js
+++ b/07_JS_Object_Arguments/Ch7_pgm_04.js
@@ -4,6 +4,8 @@ var point1;
var point2;
var move;
var showPoint;
+var reflectX;
+var rotate90;
move = function (point, change) {
return {
@@ -16,6 +18,20 @@ showPoint = function (point) {
console.log("( " + point.x + " , " + point.y + " )");
};
+reflectX = function (point) {
+ return {
+ x: point.x,
+ y: -point.y
+ };
+};
+
+rotate90 = function (point) {
+ return {
+ x: -point.y,
+ y: point.x
+ };
+};
+
point1 = { x : 2, y : 5 };
point2 = move(point1, { x : 4, y : -2 });
@@ -24,7 +40,15 @@ showPoint(point1);
console.log("Move 4 across and 2 down");
showPoint(point2);
+// Example of reflectX function
+var reflectedPoint = reflectX(point1);
+console.log("Reflect point1 in the x-axis:");
+showPoint(reflectedPoint);
+// Example of rotate90 function
+var rotatedPoint = rotate90(point1);
+console.log("Rotate point1 by 90 degrees anticlockwise:");
+showPoint(rotatedPoint);
/* Further Adventures
*
diff --git a/07_JS_Object_Arguments/Ch7_pgm_05.js b/07_JS_Object_Arguments/Ch7_pgm_05.js
index e108274..d4cef92 100644
--- a/07_JS_Object_Arguments/Ch7_pgm_05.js
+++ b/07_JS_Object_Arguments/Ch7_pgm_05.js
@@ -9,8 +9,19 @@ var showSmaller = function (num1, num2) {
showSmaller(12, 3);
showSmaller(-10, 3);
+showSmaller(3,0,8);
+var showLarger = function(num1, num2, num3){
+ var small = Math.min(num1, num2, num3);
+ var large1 = Math.max(num1, num2);
+ var large2 = Math.max(num2,num3);
+ console.log(small + " is smaller than " + large1 + " and " + large2);
+};
+
+showLarger(3,-9,7);
+showLarger(9,10,68);
+showLarger(4,0,-4);
/* Further Adventures
*
diff --git a/07_JS_Object_Arguments/Ch7_pgm_06.js b/07_JS_Object_Arguments/Ch7_pgm_06.js
index 6389c77..4a0a464 100644
--- a/07_JS_Object_Arguments/Ch7_pgm_06.js
+++ b/07_JS_Object_Arguments/Ch7_pgm_06.js
@@ -1,15 +1,50 @@
// Using Math.min and Math.max to constrain an argument
var line = function (lineLength) {
- var line = "========================================";
- lineLength = Math.max(0, lineLength);
- lineLength = Math.min(40, lineLength);
- return line.substr(0, lineLength);
- };
-
- console.log(line(30));
- console.log(line(40));
- console.log(line(50));
+ var line = "========================================";
+ lineLength = Math.max(0, lineLength);
+ lineLength = Math.min(40, lineLength);
+ return line.substr(0, lineLength);
+};
+
+for (var i = -20; i <= 60; i += 10) {
+ console.log("Length: " + i + ", Line: " + line(i));
+}
+
+
+var spaces = function (spaceLength) {
+ var spaces = " ";
+ spaceLength = Math.max(0, spaceLength);
+ spaceLength = Math.min(40, spaceLength);
+ return spaces.substr(0, spaceLength);
+};
+// Test spaces function
+console.log(spaces(15)); // Output: " "
+console.log(spaces(40)); // Output: " "
+console.log(spaces(50)); // Output: "
+
+
+var emptyBox = function (boxWidth) {
+ boxWidth = Math.max(0, boxWidth);
+ boxWidth = Math.min(40, boxWidth);
+
+ var topBottom = line(boxWidth);
+ var middle = "=" + spaces(boxWidth - 2) + "=";
+
+ console.log(topBottom);
+ for (var i = 0; i < 3; i++) {
+ console.log(middle);
+ }
+ console.log(topBottom);
+};
+
+// Test emptyBox function
+emptyBox(12);
+
+
+console.log(line(30));
+console.log(line(40));
+console.log(line(50));
diff --git a/07_JS_Object_Arguments/Ch7_pgm_07.js b/07_JS_Object_Arguments/Ch7_pgm_07.js
index 3cc9656..31aacba 100644
--- a/07_JS_Object_Arguments/Ch7_pgm_07.js
+++ b/07_JS_Object_Arguments/Ch7_pgm_07.js
@@ -2,10 +2,19 @@
var planet = "Jupiter";
var bigPlanet = planet.toUpperCase();
-
+var getBig = function (str) {
+ return str.toUpperCase();
+};
console.log(planet + " becomes " + bigPlanet);
+var getSmall = function (str) {
+ return str.toLowerCase();
+};
+// Testing getSmall function
+var country = "UNITED STATES";
+var smallCountry = getSmall(country);
+console.log(country + " becomes " + smallCountry);
/* Further Adventures
*
diff --git a/07_JS_Object_Arguments/Ch7_pgm_08.js b/07_JS_Object_Arguments/Ch7_pgm_08.js
index 7b101a7..49ee93c 100644
--- a/07_JS_Object_Arguments/Ch7_pgm_08.js
+++ b/07_JS_Object_Arguments/Ch7_pgm_08.js
@@ -3,6 +3,13 @@
var message = "We choose to go to the Moon!";
console.log(message.substr(3, 12));
+console.log(message.substr(20)); // Logs "Moon!"
+console.log(message.substr(11, 6)); // Logs "go to the"
+console.log(message.substr(0, 10));
+console.log(message.substr(3)); // Logs "choose to go to the Moon!"
+console.log(message.substr(-5)); // Logs "Moon!"
+console.log(message.substr(11, -3)); // Logs "go to the"
+// using message.substr(-5) starts from the 5th character from the end (Moon!). message.substr(11, -3) starts from index 11 and ignores the last 3 characters (go to the).
diff --git a/07_JS_Object_Arguments/Ch7_pgm_09.js b/07_JS_Object_Arguments/Ch7_pgm_09.js
index 0b058df..598a4cb 100644
--- a/07_JS_Object_Arguments/Ch7_pgm_09.js
+++ b/07_JS_Object_Arguments/Ch7_pgm_09.js
@@ -6,6 +6,19 @@ var charIndex = message.indexOf("M");
console.log(message.substr(charIndex, 3));
+var startIndex = message.indexOf("go");
+console.log(startIndex);
+
+var message = "We choose to go to the Moon!";
+
+var startIndexOfChoose = message.indexOf("choose");
+var choose = message.substr(startIndexOfChoose, 6); // "choose" has 6 characters
+console.log(choose); // Logs "choose"
+
+var message = "We choose to go to the Moon!";
+
+var lastIndex = message.lastIndexOf("oo");
+console.log(lastIndex); // Logs the index of "oo" in "Moon"
/* Further Adventures
diff --git a/08_JS_Arrays/Ch8_pgm_01.js b/08_JS_Arrays/Ch8_pgm_01.js
index efbf6d9..d8712b7 100644
--- a/08_JS_Arrays/Ch8_pgm_01.js
+++ b/08_JS_Arrays/Ch8_pgm_01.js
@@ -1,14 +1,14 @@
// Creating arrays
-
var scores;
var names;
-scores = [ 3, 1, 8, 2 ];
-names = [ "Kandra", "Dax", "Blinky" ];
+scores = [ 3, 1, 8, 2, 5];
+names = [ "Kandra", "Dax", "Blinky", "Browiee"];
+var akaScores = scores;
console.log(scores);
console.log(names);
-
+console.log(akaScores);
/* Further Adventures
diff --git a/08_JS_Arrays/Ch8_pgm_02.js b/08_JS_Arrays/Ch8_pgm_02.js
index ca5e4f9..73b2d46 100644
--- a/08_JS_Arrays/Ch8_pgm_02.js
+++ b/08_JS_Arrays/Ch8_pgm_02.js
@@ -5,7 +5,7 @@ var place2 = { name : "The Grand Canyon", country : "USA" };
var place3 = { name : "Bondi Beach", country : "Australia" };
var thisYear = [ place1, place2 ];
-var nextYear = [ place3 ];
+var nextYear = [ place3, place1]; //yes there can be two arrays
console.log(thisYear);
console.log(nextYear);
diff --git a/08_JS_Arrays/Ch8_pgm_03.js b/08_JS_Arrays/Ch8_pgm_03.js
index b47fd74..3cce98e 100644
--- a/08_JS_Arrays/Ch8_pgm_03.js
+++ b/08_JS_Arrays/Ch8_pgm_03.js
@@ -1,12 +1,14 @@
// Accessing array elements
-var scores = [ 3, 1, 8, 2 ];
+var scores = [ 3, 1, 8, 2, 5, 9];
console.log("There are " + scores.length + " scores:");
console.log("The first score is " + scores[0]);
console.log("The second score is " + scores[1]);
console.log("The third score is " + scores[2]);
console.log("The fourth score is " + scores[3]);
+console.log("The fifth score is " + scores[4]);
+console.log("The last score is " + scores[5]);
diff --git a/08_JS_Arrays/Ch8_pgm_04.js b/08_JS_Arrays/Ch8_pgm_04.js
index 25d8359..ed338fb 100644
--- a/08_JS_Arrays/Ch8_pgm_04.js
+++ b/08_JS_Arrays/Ch8_pgm_04.js
@@ -1,11 +1,21 @@
// Using a variable as an index
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
-var dayInWeek = 4;
+var dayInWeek = 3;
console.log( days[dayInWeek] );
console.log( days[dayInWeek - 1] );
+var getDay = function(dayNumber) {
+ var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
+ if (dayNumber >= 0 && dayNumber < days.length) {
+ return days[dayNumber];
+ } else {
+ return "Invalid day number";
+ }
+};
+console.log(getDay(4));
+
/* Further Adventures
diff --git a/08_JS_Arrays/Ch8_pgm_05.js b/08_JS_Arrays/Ch8_pgm_05.js
index 072418c..65e9814 100644
--- a/08_JS_Arrays/Ch8_pgm_05.js
+++ b/08_JS_Arrays/Ch8_pgm_05.js
@@ -1,30 +1,37 @@
// Passing an array to a function
var getVisitorReport = function (visitorArray, dayInWeek) {
- var days = [
- "Monday",
- "Tuesday",
- "Wednesday",
- "Thursday",
- "Friday"
+ var days = [
+ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
];
- var index = dayInWeek - 1;
- var visitorReport;
+ var index = dayInWeek - 1;
+ var visitorReport;
- visitorReport = "There were ";
+ visitorReport = "There were ";
visitorReport += visitorArray[index];
visitorReport += " visitors ";
- visitorReport += "on " + days[index];
+ visitorReport += "on " + days[index];
- return visitorReport;
+ return visitorReport;
};
-var visitors = [ 354, 132, 210, 221, 481 ];
+var getMonthlyVisitorReport = function (monthArray, week, dayInWeek) {
+ var weekArray = monthArray[week - 1];
+ return getVisitorReport(weekArray, dayInWeek);
+};
+
+var week1 = [354, 132, 210, 221, 481, 290, 150];
+var week2 = [124, 432, 190, 241, 301, 280, 160];
+var week3 = [334, 142, 250, 221, 431, 270, 180];
+var week4 = [254, 122, 230, 211, 371, 260, 140];
-var report = getVisitorReport(visitors, 2);
+var month = [week1, week2, week3, week4];
-console.log(report);
+var report1 = getVisitorReport(week1, 5); // Friday of week 1
+console.log(report1); // Should log "There were 481 visitors on Friday"
+var monthlyReport = getMonthlyVisitorReport(month, 2, 5); // Week 2, Friday
+console.log(monthlyReport); // Should log "There were 301 visitors on Friday"
/* Further Adventures
diff --git a/08_JS_Arrays/Ch8_pgm_06.js b/08_JS_Arrays/Ch8_pgm_06.js
index 5a279b6..35f8fac 100644
--- a/08_JS_Arrays/Ch8_pgm_06.js
+++ b/08_JS_Arrays/Ch8_pgm_06.js
@@ -1,5 +1,4 @@
// Manipulating arrays with push, pop and join
-
var items = [];
var item = "The Pyramids";
var removed;
@@ -15,6 +14,12 @@ removed = items.pop();
console.log(removed + " was removed");
console.log(items.join(" and "));
+items.push("The great artist");
+console.log(items.join(" and "));
+item[1] = "The theme park";
+console.log(items.join(" and "));
+items.push("The Warner Bros", "Disney Island");
+console.log(items.join(" and "));
/* Further Adventures
diff --git a/08_JS_Arrays/Ch8_pgm_07.js b/08_JS_Arrays/Ch8_pgm_07.js
index ac276cd..c5363ad 100644
--- a/08_JS_Arrays/Ch8_pgm_07.js
+++ b/08_JS_Arrays/Ch8_pgm_07.js
@@ -1,20 +1,31 @@
// Iterating over an array with forEach
-
var items;
var showInfo;
items = [
"The Pyramids",
"The Grand Canyon",
- "Bondi Beach"
+ "Bondi Beach",
+ "Effiel Tower",
+ "Taj Mahal",
+ "The Great Wall of China"
];
showInfo = function (itemToShow) {
- console.log(itemToShow);
+ console.log(itemToShow + " has " + itemToShow.length + " of letters");
};
items.forEach(showInfo);
+var totalLetters = function(itemsArray){
+ var total = 0;
+ itemsArray.forEach(function(item){
+ total += item.length;
+ });
+ return total;
+};
+console.log("Total number of letters in the array is " + totalLetters(items));
+
/* Further Adventures
diff --git a/08_JS_Arrays/Ch8_pgm_08.js b/08_JS_Arrays/Ch8_pgm_08.js
index 06c94b5..ef535bd 100644
--- a/08_JS_Arrays/Ch8_pgm_08.js
+++ b/08_JS_Arrays/Ch8_pgm_08.js
@@ -2,11 +2,17 @@
var items = [ "The Pyramids", "The Grand Canyon", "Bondi Beach" ];
-console.log("Dream destinations:");
+var showItems = function () {
+ console.log("Dream destinations (" + items.length + " places to visit):");
+ items.forEach(function (item) {
+ console.log(" – " + item);
+ });
+};
-items.forEach(function (item) {
- console.log(" – " + item);
-});
+// Initial display of items
+showItems();
+//in console by typing showItems() we can run the program
+// Also using pop we can remove the items in the console prompt
diff --git a/08_JS_Arrays/Ch8_pgm_09.js b/08_JS_Arrays/Ch8_pgm_09.js
index 3680f1d..289cf89 100644
--- a/08_JS_Arrays/Ch8_pgm_09.js
+++ b/08_JS_Arrays/Ch8_pgm_09.js
@@ -3,17 +3,19 @@
var players;
var showArguments;
-players = [ "Dax", "Jahver", "Kandra" ];
+players = [ "Dax", "Jahver", "Kandra"];
+
+players.push("Jaddu");
+players.push("Virat");
showArguments = function (item, index, wholeArray) {
- console.log("Item: " + item);
+ console.log("Item: " + wholeArray[index]);
console.log("Index: " + index);
console.log("Array: " + wholeArray);
};
players.forEach(showArguments);
-
/* Further Adventures
*
* 1) Add two more names to the players array.
diff --git a/08_JS_Arrays/Ch8_pgm_10.js b/08_JS_Arrays/Ch8_pgm_10.js
index 2f8a9d2..2164ded 100644
--- a/08_JS_Arrays/Ch8_pgm_10.js
+++ b/08_JS_Arrays/Ch8_pgm_10.js
@@ -1,12 +1,41 @@
// Using the arguments passed by forEach - compact
+// Original code for players array
[ "Dax", "Jahver", "Kandra" ].forEach(function (item, index, wholeArray) {
- console.log("Item: " + item);
- console.log("Index: " + index);
- console.log("Array: " + wholeArray);
- });
-
-
+ console.log("Item: " + item);
+ console.log("Index: " + index);
+ console.log("Array: " + wholeArray);
+});
+
+// Rectangle array
+var rect = [
+ { length: 5, width: 3 },
+ { length: 10, width: 4 },
+ { length: 6, width: 6 },
+ { length: 7, width: 2 },
+ { length: 8, width: 5 }
+];
+
+// Function to assign area to a rectangle
+var assignArea = function(rect) {
+ rect.area = rect.length * rect.width;
+};
+
+// Function to display rectangle info
+var showInfo = function(rect) {
+ console.log("Length: " + rect.length);
+ console.log("Width: " + rect.width);
+ console.log("Area: " + rect.area);
+};
+
+// Assign area to each rectangle and display info
+rect.forEach(function(rect) {
+ assignArea(rect);
+ showInfo(rect);
+});
+
+// Example to show the array with assigned areas
+console.log(rect);
/* Further Adventures
*
diff --git a/08_JS_Arrays/Ch8_pgm_11.js b/08_JS_Arrays/Ch8_pgm_11.js
index 58561c6..13a5ce3 100644
--- a/08_JS_Arrays/Ch8_pgm_11.js
+++ b/08_JS_Arrays/Ch8_pgm_11.js
@@ -1,20 +1,26 @@
// Finding the total shopping bill
-var getTotalBill = function (itemCosts, itemCounts) {
+var getTotalBill = function (items) {
var total = 0;
- itemCosts.forEach(function (cost, i) {
- total += cost * itemCounts[i];
+ items.forEach(function (item) {
+ total += item.cost * item.numberBought;
});
return total;
};
-var costs = [ 1.99, 4.95, 2.50, 9.87 ];
-var numOfEach = [ 2, 1, 5, 2 ];
-
-console.log("The total cost is $" + getTotalBill(costs, numOfEach));
-
+var items = [
+ { cost: 1.99, numberBought: 2 },
+ { cost: 4.95, numberBought: 1 },
+ { cost: 2.50, numberBought: 5 },
+ { cost: 9.87, numberBought: 2 },
+ // Add an extra item to the shopping trip
+ { cost: 3.75, numberBought: 4 }
+];
+
+// Calculate and log the total cost
+console.log("The total cost is $" + getTotalBill(items));
/* Further Adventures
diff --git a/08_JS_Arrays/Ch8_pgm_12.js b/08_JS_Arrays/Ch8_pgm_12.js
index 2327cc8..2272c98 100644
--- a/08_JS_Arrays/Ch8_pgm_12.js
+++ b/08_JS_Arrays/Ch8_pgm_12.js
@@ -1,31 +1,53 @@
// Displaying a multiple choice question
var displayQuestion = function (questionAndAnswer) {
- var options = [ "A", "B", "C", "D", "E" ];
-
- console.log(questionAndAnswer.question);
-
- questionAndAnswer.answers.forEach(
- function (answer, i) {
- console.log(options[i] + " - " + answer);
- }
- );
- };
-
- var question1 = {
- question : "What is the capital of France?",
- answers : [
- "Bordeaux",
- "F",
- "Paris",
- "Brussels"
- ],
- correctAnswer : "Paris"
- };
-
- displayQuestion(question1);
+ var options = [ "A", "B", "C", "D", "E" ];
+ console.log(questionAndAnswer.question);
+ questionAndAnswer.answers.forEach(
+ function (answer, i) {
+ console.log(options[i] + " - " + answer);
+ }
+ );
+};
+
+var question1 = {
+ question : "What is the capital of France?",
+ answers : [
+ "Bordeaux",
+ "F",
+ "Paris",
+ "Brussels"
+ ],
+ correctAnswer : "Paris"
+};
+
+var question2 = {
+ question : "Where did the effiel tower located?",
+ answers : [
+ "Paris",
+ "France",
+ "Australia",
+ "India"
+ ],
+ correctAnswer : "Paris"
+};
+
+var question3 = {
+ question : "What is the capital of India?",
+ answers : [
+ "Tamil Nadu",
+ "Bombay",
+ "Paris",
+ "New Delhi"
+ ],
+ correctAnswer : "New Delhi"
+};
+displayQuestion(question1);
+displayQuestion(question2);
+displayQuestion(question3);
+
/* Further Adventures
*
diff --git a/08_JS_Arrays/Ch8_pgm_13.js b/08_JS_Arrays/Ch8_pgm_13.js
index 5816527..0990b28 100644
--- a/08_JS_Arrays/Ch8_pgm_13.js
+++ b/08_JS_Arrays/Ch8_pgm_13.js
@@ -1,108 +1,127 @@
var spacer = {
- blank: function () {
- return "";
- },
-
- newLine: function () {
- return "\n";
- },
-
- line: function (length, character) {
- var longString = "****************************************";
- longString += "----------------------------------------";
- longString += "========================================";
- longString += "++++++++++++++++++++++++++++++++++++++++";
- longString += " ";
-
- length = Math.max(0, length);
- length = Math.min(40, length);
- return longString.substr(longString.indexOf(character), length);
- },
-
- wrap : function (text, length, character) {
- var padLength = length - text.length - 3;
- var wrapText = character + " " + text;
- wrapText += spacer.line(padLength, " ");
- wrapText += character;
- return wrapText;
- },
-
- box: function (text, length, character) {
- var boxText = spacer.newLine();
- boxText += spacer.line(length, character) + spacer.newLine();
- boxText += spacer.wrap(text, length, character) + spacer.newLine();
- boxText += spacer.line(length, character) + spacer.newLine();
- return boxText;
- }
- };
-
-
- // Player display code
-
- var getPlayerName = function (player) {
- return player.name;
- };
-
- var getPlayerHealth = function (player) {
- return player.name + " has health " + player.health;
- };
-
- var getPlayerPlace = function (player) {
- return player.name + " is in " + player.place;
- };
-
- var getPlayerItems = function (player) {
- var itemsString = "Items:" + spacer.newLine();
-
- player.items.forEach(function (item) {
- itemsString += " - " + item + spacer.newLine();
- });
-
- return itemsString;
- };
-
- var getPlayerInfo = function (player, character) {
- var place = getPlayerPlace(player);
- var health = getPlayerHealth(player);
- var longest = Math.max(place.length, health.length) + 4;
-
- var info = spacer.box(getPlayerName(player), longest, character);
- info += spacer.wrap(place, longest, character);
- info += spacer.newLine() + spacer.wrap(health, longest, character);
- info += spacer.newLine() + spacer.line(longest, character);
-
- info += spacer.newLine();
- info += " " + getPlayerItems(player);
- info += spacer.newLine();
- info += spacer.line(longest, character);
-
- info += spacer.newLine();
-
- return info;
- };
-
- var showPlayerInfo = function (player, character) {
- console.log(getPlayerInfo(player, character));
- };
-
-
- // Create a player
-
- var player1 = {
- name: "Kandra",
- place: "The Dungeon of Doom",
- health: 50,
- items : ["a trusty lamp"]
- };
-
- showPlayerInfo(player1, "=");
-
- player1.items.push("a rusty key");
-
- showPlayerInfo(player1, "*");
-
-
-
+ blank: function () {
+ return "";
+ },
+
+ newLine: function () {
+ return "\n";
+ },
+
+ line: function (length, character) {
+ var longString = "****************************************";
+ longString += "----------------------------------------";
+ longString += "========================================";
+ longString += "++++++++++++++++++++++++++++++++++++++++";
+ longString += " ";
+
+ length = Math.max(0, length);
+ length = Math.min(40, length);
+ return longString.substr(longString.indexOf(character), length);
+ },
+
+ wrap : function (text, length, character) {
+ var padLength = length - text.length - 3;
+ var wrapText = character + " " + text;
+ wrapText += spacer.line(padLength, " ");
+ wrapText += character;
+ return wrapText;
+ },
+
+ box: function (text, length, character) {
+ var boxText = spacer.newLine();
+ boxText += spacer.line(length, character) + spacer.newLine();
+ boxText += spacer.wrap(text, length, character) + spacer.newLine();
+ boxText += spacer.line(length, character) + spacer.newLine();
+ return boxText;
+ }
+};
+
+
+// Player display code
+
+var getPlayerName = function (player) {
+ return player.name;
+};
+
+var getPlayerHealth = function (player) {
+ return player.name + " has health " + player.health;
+};
+
+var getPlayerPlace = function (player) {
+ return player.name + " is in " + player.place;
+};
+
+var getPlayerItems = function (player) {
+ var itemsString = "Items:" + spacer.newLine();
+
+ player.items.forEach(function (item) {
+ itemsString += " - " + item + spacer.newLine();
+ });
+
+ return itemsString;
+};
+
+var getPlayerInfo = function (player, character) {
+ var place = getPlayerPlace(player);
+ var health = getPlayerHealth(player);
+ var longest = Math.max(place.length, health.length) + 4;
+
+ var info = spacer.box(getPlayerName(player), longest, character);
+ info += spacer.wrap(place, longest, character);
+ info += spacer.newLine() + spacer.wrap(health, longest, character);
+ info += spacer.newLine() + spacer.line(longest, character);
+
+ info += spacer.newLine();
+ info += " " + getPlayerItems(player);
+ info += spacer.newLine();
+ info += spacer.line(longest, character);
+
+ info += spacer.newLine();
+
+ return info;
+};
+
+var showPlayerInfo = function (player, character) {
+ console.log(getPlayerInfo(player, character));
+};
+
+
+// Create a player
+
+var player1 = {
+ name: "Kandra",
+ place: "The Dungeon of Doom",
+ health: 50,
+ items : ["a trusty lamp"]
+};
+
+showPlayerInfo(player1, "=");
+
+player1.items.push("a rusty key");
+
+showPlayerInfo(player1, "*");
+var showItem = function (player, itemNumber) {
+ if (itemNumber >= 1 && itemNumber <= player.items.length) {
+ console.log(player.name + "'s item " + itemNumber + ": " + player.items[itemNumber - 1]);
+ } else {
+ console.log("Item number is out of range.");
+ }
+};
+showItem(player1,1);
+showItem(player1, 2); // Displaying the second item
+
+// 4) Add an item to the player's item array
+var addItem = function (player, itemTitle) {
+ player.items.push(itemTitle);
+ console.log(itemTitle + " added to " + player.name + "'s items.");
+};
+
+addItem(player1, "a magic potion");
+showPlayerInfo(player1, "=");
+// Display updated player info
+showItem(player1,1);
+showItem(player1, 2);
+showItem(player1,3)
/* Further Adventures
*
diff --git a/09_JS_Constructors/Ch9_pgm_01.js b/09_JS_Constructors/Ch9_pgm_01.js
index fb69a8e..1ac40db 100644
--- a/09_JS_Constructors/Ch9_pgm_01.js
+++ b/09_JS_Constructors/Ch9_pgm_01.js
@@ -1,5 +1,4 @@
// Using a function to create an object
-
var buildPlanet = function (name, position, type) {
var planet = {};
@@ -15,11 +14,19 @@ var planet1 = buildPlanet(
5,
"Gas Giant"
);
+var planet2 = buildPlanet(
+ "Earth",
+ 3,
+ "The world"
+)
console.log(planet1.name);
console.log(planet1.position);
console.log(planet1.type);
+console.log(planet2.name);
+console.log(planet2.position);
+console.log(planet2.type);
/* Further Adventures
diff --git a/09_JS_Constructors/Ch9_pgm_02.js b/09_JS_Constructors/Ch9_pgm_02.js
index 0eac8a9..43b93a6 100644
--- a/09_JS_Constructors/Ch9_pgm_02.js
+++ b/09_JS_Constructors/Ch9_pgm_02.js
@@ -23,7 +23,15 @@ var planet1 = buildPlanet(
"Gas Giant"
);
+var planet2 = buildPlanet(
+ "Earth",
+ 3,
+ "The world"
+)
+
+
planet1.showPlanet();
+planet2.showPlanet();
diff --git a/09_JS_Constructors/Ch9_pgm_03.js b/09_JS_Constructors/Ch9_pgm_03.js
index a74a04a..532a00a 100644
--- a/09_JS_Constructors/Ch9_pgm_03.js
+++ b/09_JS_Constructors/Ch9_pgm_03.js
@@ -12,6 +12,7 @@ var buildPlanet = function (name, position, type) {
info += ": planet " + planet.position;
info += " - " + planet.type;
console.log(info);
+ console.log("========================")
};
return planet;
@@ -20,15 +21,14 @@ var buildPlanet = function (name, position, type) {
var planets = [
buildPlanet( "Jupiter", 5, "Gas Giant" ),
buildPlanet( "Neptune", 8, "Ice Giant" ),
- buildPlanet( "Mercury", 1, "Terrestrial" )
+ buildPlanet( "Mercury", 1, "Terrestrial" ),
+ buildPlanet( "Earth", 3, "The World"),
+ buildPlanet( "Venus", 2, "Coolest Planet")
];
planets.forEach(function (planet) {
planet.showPlanet();
});
-
-
-
/* Further Adventures
*
* 1) Add two more planets to the planets array.
diff --git a/09_JS_Constructors/Ch9_pgm_04.js b/09_JS_Constructors/Ch9_pgm_04.js
index 9337505..f83d808 100644
--- a/09_JS_Constructors/Ch9_pgm_04.js
+++ b/09_JS_Constructors/Ch9_pgm_04.js
@@ -13,9 +13,14 @@ var Planet = function (name, position, type) {
};
var planet = new Planet( "Jupiter", 5, "Gas Giant" );
+var planet1 = new Planet(
+ "Earth",
+ 3,
+ "The World"
+);
planet.showPlanet();
-
+planet1.showPlanet();
/* Further Adventures
diff --git a/09_JS_Constructors/Ch9_pgm_05.js b/09_JS_Constructors/Ch9_pgm_05.js
index 9d3725d..98ffe3b 100644
--- a/09_JS_Constructors/Ch9_pgm_05.js
+++ b/09_JS_Constructors/Ch9_pgm_05.js
@@ -16,15 +16,37 @@ var Planet = function (name, position, type) {
this.addMoon = function (moon) {
this.moons.push(moon);
};
+ this.removeMoon = function() {
+ if (this.moons.length > 0) {
+ this.moons.pop();
+ } else {
+ console.log("No moons to remove.");
+ }
+ };
};
var planet = new Planet( "Jupiter", 5, "Gas Giant" );
+var planet1 = new Planet(
+ "Earth",
+ 3,
+ "The World"
+);
planet.addMoon("Io");
planet.addMoon("Europa");
planet.showPlanet();
+planet1.addMoon("Io");
+planet1.addMoon("Europa");
+planet1.addMoon("Continent");
+planet1.addMoon("Australia");
+planet1.removeMoon();
+
+planet1.showPlanet();
+
+
+
/* Further Adventures
diff --git a/09_JS_Constructors/Ch9_pgm_06.js b/09_JS_Constructors/Ch9_pgm_06.js
index d9d63b1..a62a407 100644
--- a/09_JS_Constructors/Ch9_pgm_06.js
+++ b/09_JS_Constructors/Ch9_pgm_06.js
@@ -13,22 +13,39 @@ var Planet = function (name, position, type) {
this.addMoon = function (moon) {
this.moons.unshift(moon);
};
+ this.getMoon = function(index) {
+ if (index >= 0 && index < this.moons.length) {
+ return this.moons[index];
+ } else {
+ return "No moon found at index " + index;
+ }
+ };
};
var planet1 = new Planet("Jupiter", 5, "Gas Giant");
planet1.addMoon("Io");
planet1.addMoon("Europa");
+planet1.addMoon("Australia");
var planet2 = new Planet("Neptune", 8, "Ice Giant");
planet2.addMoon("Triton");
+planet2.addMoon("France");
var planet3 = new Planet("Mercury", 1, "Terrestrial");
+planet3.addMoon("Io");
[ planet1, planet2, planet3 ].forEach(function (planet) {
planet.showPlanet();
});
-
+console.log("> planet1.getMoon(1)");
+console.log(planet1.getMoon(1));
+console.log("> planet2.getMoon(0)");
+console.log(planet2.getMoon(0));
+console.log("> planet3.getMoon(2)");
+console.log(planet3.getMoon(2));
+console.log("> planet1.getMoon(3)");
+console.log(planet1.getMoon(3));
/* Further Adventures
*
diff --git a/09_JS_Constructors/Ch9_pgm_07.js b/09_JS_Constructors/Ch9_pgm_07.js
index 3dfc249..f4b70a0 100644
--- a/09_JS_Constructors/Ch9_pgm_07.js
+++ b/09_JS_Constructors/Ch9_pgm_07.js
@@ -26,9 +26,37 @@ question1.addOption("Bordeaux");
question1.addOption("F");
question1.addOption("Paris");
question1.addOption("Brussels");
+question1.addOption("Swedan");
question1.showQuestion();
+var question2 = new QuizQuestion(
+ "What is the capital of India?",
+ "New Delhi"
+);
+
+question2.addOption("Bombay");
+question2.addOption("Agra");
+question2.addOption("Paris");
+question2.addOption("J&K");
+question2.addOption("TN");
+
+question2.showQuestion();
+
+var question3 = new QuizQuestion(
+ "What is the national animal of India?",
+ "Tiger"
+);
+
+question3.addOption("Lion");
+question3.addOption("Horse");
+question3.addOption("Tiger");
+question3.addOption("Cat");
+question3.addOption("Elephant");
+
+question3.showQuestion();
+// by typing the question2.answer in the console we get the question2 answer.
+
/* Further Adventures
diff --git a/09_JS_Constructors/Ch9_pgm_08.js b/09_JS_Constructors/Ch9_pgm_08.js
index fbf1005..2803346 100644
--- a/09_JS_Constructors/Ch9_pgm_08.js
+++ b/09_JS_Constructors/Ch9_pgm_08.js
@@ -1,5 +1,4 @@
// A calendar event constructor
-
var CalendarEvent = function (title, startDate, startTime, endTime) {
this.title = title;
this.startDate = startDate;
@@ -9,14 +8,13 @@ var CalendarEvent = function (title, startDate, startTime, endTime) {
this.showEvent = function () {
var dateString = [
this.startDate,
- ", from ",
+ " - (",
this.startTime,
- " to ",
- this.endTime
+ " - ",
+ this.endTime, ")"
].join("");
- console.log(this.title);
- console.log(dateString);
+ console.log(this.title + ": " + dateString);
};
};
@@ -27,9 +25,17 @@ var calEvent = new CalendarEvent(
"5.00pm"
);
-calEvent.showEvent();
+var calEvent2 = new CalendarEvent(
+ "Conference",
+ "3/9/23",
+ "2.00pm",
+ "5.00pm"
+);
+
+calEvent.showEvent();
+calEvent2.showEvent();
/* Further Adventures
*
diff --git a/09_JS_Constructors/Ch9_pgm_09.js b/09_JS_Constructors/Ch9_pgm_09.js
index b9f70b8..e54b0de 100644
--- a/09_JS_Constructors/Ch9_pgm_09.js
+++ b/09_JS_Constructors/Ch9_pgm_09.js
@@ -1,184 +1,207 @@
// A Player constructor function
var spacer = {
- blank: function () {
- return "";
- },
-
- newLine: function () {
- return "\n";
- },
-
- line: function (length, character) {
- var longString = "****************************************";
- longString += "----------------------------------------";
- longString += "========================================";
- longString += "++++++++++++++++++++++++++++++++++++++++";
- longString += " ";
-
- length = Math.max(0, length);
- length = Math.min(40, length);
- return longString.substr(longString.indexOf(character), length);
- },
-
- wrap : function (text, length, character) {
- var padLength = length - text.length - 3;
- var wrapText = character + " " + text;
- wrapText += spacer.line(padLength, " ");
- wrapText += character;
- return wrapText;
- },
-
- box: function (text, length, character) {
- var boxText = spacer.newLine();
- boxText += spacer.line(length, character) + spacer.newLine();
- boxText += spacer.wrap(text, length, character) + spacer.newLine();
- boxText += spacer.line(length, character) + spacer.newLine();
- return boxText;
- }
- };
-
-
- // The Place constructor
-
- var Place = function (title, description) {
- var newLine = spacer.newLine();
-
- this.title = title;
- this.description = description;
- this.items = [];
- this.exits = [];
-
- this.getItemsInfo = function () {
- var itemsString = "Items: " + newLine;
- this.items.forEach(function (item) {
- itemsString += " - " + item;
- itemsString += newLine;
- });
- return itemsString;
- };
-
- this.getExitsInfo = function () {
- var exitsString = "Exits from " + this.title;
- exitsString += ":" + newLine;
-
- this.exits.forEach(function (exit) {
- exitsString += " - " + exit.title;
- exitsString += newLine;
- });
-
- return exitsString;
- };
-
- this.getTitleInfo = function () {
- return spacer.box(
- this.title,
- this.title.length + 4,
- "="
- );
- };
-
- this.getInfo = function () {
- var infoString = this.getTitleInfo();
- infoString += this.description;
- infoString += newLine + newLine;
- infoString += this.getItemsInfo() + newLine;
- infoString += this.getExitsInfo();
- infoString += spacer.line(40, "=") + newLine;
- return infoString;
- };
-
-
- this.showInfo = function () {
- console.log(this.getInfo());
- };
-
- this.addItem = function (item) {
- this.items.push(item);
- };
-
- this.addExit = function (exit) {
- this.exits.push(exit);
- };
- };
-
-
- // The Player constructor
-
- var Player = function (name, health) {
+ blank: function () {
+ return "";
+ },
+
+ newLine: function () {
+ return "\n";
+ },
+
+ line: function (length, character) {
+ var longString = "****************************************";
+ longString += "----------------------------------------";
+ longString += "========================================";
+ longString += "++++++++++++++++++++++++++++++++++++++++";
+ longString += " ";
+
+ length = Math.max(0, length);
+ length = Math.min(40, length);
+ return longString.substr(longString.indexOf(character), length);
+ },
+
+ wrap : function (text, length, character) {
+ var padLength = length - text.length - 3;
+ var wrapText = character + " " + text;
+ wrapText += spacer.line(padLength, " ");
+ wrapText += character;
+ return wrapText;
+ },
+
+ box: function (text, length, character) {
+ var boxText = spacer.newLine();
+ boxText += spacer.line(length, character) + spacer.newLine();
+ boxText += spacer.wrap(text, length, character) + spacer.newLine();
+ boxText += spacer.line(length, character) + spacer.newLine();
+ return boxText;
+ }
+};
+
+
+// The Place constructor
+
+var Place = function (title, description) {
var newLine = spacer.newLine();
-
- this.name = name;
- this.health = health;
+
+ this.title = title;
+ this.description = description;
this.items = [];
- this.place = null;
-
- this.addItem = function (item) {
- this.items.push(item);
+ this.exits = [];
+
+ this.getItemsInfo = function () {
+ var itemsString = "Items: " + newLine;
+ this.items.forEach(function (item) {
+ itemsString += " - " + item;
+ itemsString += newLine;
+ });
+ return itemsString;
};
-
- this.getNameInfo = function () {
- return this.name;
+
+ this.getExitsInfo = function () {
+ var exitsString = "Exits from " + this.title;
+ exitsString += ":" + newLine;
+
+ this.exits.forEach(function (exit) {
+ exitsString += " - " + exit.title;
+ exitsString += newLine;
+ });
+
+ return exitsString;
};
-
- this.getHealthInfo = function () {
- return this.name + " has health " + this.health;
+
+ this.getTitleInfo = function () {
+ return spacer.box(
+ this.title,
+ this.title.length + 4,
+ "="
+ );
};
-
- this.getPlaceInfo = function () {
- return this.name + " is in " + this.place.title;
+
+ this.getInfo = function () {
+ var infoString = this.getTitleInfo();
+ infoString += this.description;
+ infoString += newLine + newLine;
+ infoString += this.getItemsInfo() + newLine;
+ infoString += this.getExitsInfo();
+ infoString += spacer.line(40, "=") + newLine;
+ return infoString;
};
-
- this.getItemsInfo = function () {
- var itemsString = "Items:" + newLine;
-
- this.items.forEach(function (item, i) {
- itemsString += " - " + item + newLine;
- });
-
- return itemsString;
+
+
+ this.showInfo = function () {
+ console.log(this.getInfo());
};
-
- this.getInfo = function (character) {
- var place = this.getPlaceInfo();
- var health = this.getHealthInfo();
- var longest = Math.max(place.length, health.length) + 4;
-
- var info = spacer.box(this.getNameInfo(), longest, character);
- info += spacer.wrap(place, longest, character);
- info += spacer.newLine() + spacer.wrap(health, longest, character);
- info += newLine + spacer.line(longest, character);
-
- info += newLine;
- info += " " + this.getItemsInfo();
- info += newLine;
- info += spacer.line(longest, character);
- info += newLine;
-
- return info;
+
+ this.addItem = function (item) {
+ this.items.push(item);
};
-
- this.showInfo = function (character) {
- console.log(this.getInfo(character));
+
+ this.addExit = function (exit) {
+ this.exits.push(exit);
};
+};
+
+
+// The Player constructor
+
+var Player = function (name, health) {
+ var newLine = spacer.newLine();
+
+ this.name = name;
+ this.health = health;
+ this.items = [];
+ this.place = null;
+
+ this.addItem = function (item) {
+ this.items.push(item);
};
-
-
- // Testing Player
-
- var library = new Place(
- "The Old Library",
- "You are in a library. Dusty books line the walls."
- );
-
- var player1 = new Player("Kandra", 50);
- player1.place = library;
- player1.addItem("a rusty key");
- player1.addItem("The Sword of Doom");
-
- player1.showInfo("=");
-
-
+
+ this.getNameInfo = function () {
+ return this.name;
+ };
+
+ this.getHealthInfo = function () {
+ return this.name + " has health " + this.health;
+ };
+
+ this.getPlaceInfo = function () {
+ return this.name + " is in " + this.place.title;
+ };
+
+ this.getItemsInfo = function () {
+ var itemsString = "Items:" + newLine;
+
+ this.items.forEach(function (item, i) {
+ itemsString += " - " + item + newLine;
+ });
+
+ return itemsString;
+ };
+
+ this.getInfo = function (character) {
+ var place = this.getPlaceInfo();
+ var health = this.getHealthInfo();
+ var longest = Math.max(place.length, health.length) + 4;
+
+ var info = spacer.box(this.getNameInfo(), longest, character);
+ info += spacer.wrap(place, longest, character);
+ info += spacer.newLine() + spacer.wrap(health, longest, character);
+ info += newLine + spacer.line(longest, character);
+
+ info += newLine;
+ info += " " + this.getItemsInfo();
+ info += newLine;
+ info += spacer.line(longest, character);
+ info += newLine;
+
+ return info;
+ };
+
+ this.showInfo = function (character) {
+ console.log(this.getInfo(character));
+ };
+};
+
+
+// Testing Player
+
+var library = new Place(
+ "The Old Library",
+ "You are in a library. Dusty books line the walls."
+);
+
+var player1 = new Player("Kandra", 50);
+player1.place = library;
+player1.addItem("a rusty key");
+player1.addItem("The Sword of Doom");
+
+var player2 = new Player("Max", 40);
+player2.place = library;
+player2.addItem("bunch of keys");
+player2.addItem("The Sword titans");
+
+var player3 = new Player("Daniel", 60);
+player3.place = library;
+player3.addItem("a rusty iron");
+player1.addItem("The thunder of Doom");
+
+player1.showInfo("=");
+player2.showInfo("=");
+player3.showInfo("=");
+
+Player.prototype.dropLastItem = function () {
+ if (this.items.length > 0) {
+ return this.items.pop();
+ } else {
+ return "No items to drop.";
+ }
+};
+
+
+console.log(player1.dropLastItem());
+console.log(player2.dropLastItem());
+console.log(player3.dropLastItem());
/* Further Adventures
*
diff --git a/10_JS_Conditions/Ch10_pgm_01.js b/10_JS_Conditions/Ch10_pgm_01.js
index dd971e9..283be6a 100644
--- a/10_JS_Conditions/Ch10_pgm_01.js
+++ b/10_JS_Conditions/Ch10_pgm_01.js
@@ -3,9 +3,13 @@
var secret = 8;
var guess = function (userNumber) {
- if (userNumber === secret) {
- console.log("Well done!");
- }
+// if (userNumber === secret) {
+// console.log("Well done!");
+// }
+ if (userNumber > secret) {
+ console.log("Too High!");
+ }
+
};
diff --git a/10_JS_Conditions/Ch10_pgm_02.js b/10_JS_Conditions/Ch10_pgm_02.js
index cdb080f..7207971 100644
--- a/10_JS_Conditions/Ch10_pgm_02.js
+++ b/10_JS_Conditions/Ch10_pgm_02.js
@@ -5,13 +5,11 @@ var secret = 8;
var guess = function (userNumber) {
if (userNumber === secret) {
console.log("Well done!");
- } else {
+ } else if(userNumber !== secret){
console.log("Unlucky, try again.");
}
};
-
-
/* Further Adventures
*
* 1) Run the program and try a few guesses at the prompt.
diff --git a/10_JS_Conditions/Ch10_pgm_03.js b/10_JS_Conditions/Ch10_pgm_03.js
index 49635c4..b332087 100644
--- a/10_JS_Conditions/Ch10_pgm_03.js
+++ b/10_JS_Conditions/Ch10_pgm_03.js
@@ -1,19 +1,24 @@
// Guess the number - using local scope
var getGuesser = function () {
- var secret = 8;
-
- return function (userNumber) {
- if (userNumber === secret) {
- console.log("Well done!");
- } else {
- console.log("Unlucky, try again.");
- }
- };
+ var secret = 8;
+
+ return function (userNumber) {
+ if (userNumber === secret) {
+ console.log("Well done!");
+ } else {
+ console.log("Unlucky, try again.");
+ }
};
-
- var guess = getGuesser();
-
+};
+
+var guess = getGuesser();
+
+// while typing getGuesser it shows the getGuesser() function.
+
+//while typing guess it also shows the getGuesser() function because the guess = getGuesser().
+
+//while typing secret it shows undefined.
/* Further Adventures
diff --git a/10_JS_Conditions/Ch10_pgm_04.js b/10_JS_Conditions/Ch10_pgm_04.js
index 22cf9f8..a687874 100644
--- a/10_JS_Conditions/Ch10_pgm_04.js
+++ b/10_JS_Conditions/Ch10_pgm_04.js
@@ -1,19 +1,36 @@
// Guess the random number
-var getGuesser = function () {
- var secret = Math.floor(Math.random() * 10 + 1);
-
- return function (userNumber) {
+function getRandomNumber(min, max) {
+ return Math.floor(Math.random() * (max - min + 1)) + min;
+}
+
+
+function createGuesser(min, max) {
+ let secret = getRandomNumber(min, max);
+
+ return function guess(userNumber) {
if (userNumber === secret) {
- return "Well done!";
+ return "Well done!";
} else {
- return "Unlucky, try again.";
+ return "Unlucky, try again.";
}
- };
};
-
- var guess = getGuesser();
-
+}
+
+
+
+var guess = createGuesser(30, 50);
+
+console.log(guess(35));
+console.log(guess(40));
+
+
+function between(min, max) {
+ return Math.floor(Math.random() * (max - min + 1)) + min;
+}
+
+console.log(between(34, 50));
+console.log(between(100, 200));
/* Further Adventures
diff --git a/10_JS_Conditions/Ch10_pgm_05.js b/10_JS_Conditions/Ch10_pgm_05.js
index 71cc2b6..3672f79 100644
--- a/10_JS_Conditions/Ch10_pgm_05.js
+++ b/10_JS_Conditions/Ch10_pgm_05.js
@@ -1,24 +1,22 @@
// Higher or Lower
var getGuesser = function () {
- var secret = Math.floor(Math.random() * 10 + 1);
-
- return function (userNumber) {
+ var secret = Math.floor(Math.random() * 10 + 1);
+
+ return function (userNumber) {
+ if (userNumber < secret) {
+ return "Too low!";
+ } else {
if (userNumber === secret) {
return "Well done!";
} else {
- if (userNumber > secret) {
- return "Too high!";
- } else {
- return "Too low!";
- }
+ return "Too high!";
}
- };
+ }
};
-
- var guess = getGuesser();
-
-
+};
+
+var guess = getGuesser();
/* Further Adventures
*
diff --git a/10_JS_Conditions/Ch10_pgm_06.js b/10_JS_Conditions/Ch10_pgm_06.js
index e3f8d9d..8fe9d21 100644
--- a/10_JS_Conditions/Ch10_pgm_06.js
+++ b/10_JS_Conditions/Ch10_pgm_06.js
@@ -1,22 +1,25 @@
// A neater else-if block
-var getGuesser = function () {
- var secret = Math.floor(Math.random() * 10 + 1);
-
- return function (userNumber) {
- if (userNumber === secret) {
- return "Well done!";
- } else if (userNumber > secret) {
- return "Too high!";
- } else {
- return "Too low!";
- }
- };
+var getGuesser = function (range, offset = 0) {
+ var secret = Math.floor(Math.random() * range + 1) + offset;
+
+ return function (userNumber) {
+ if (userNumber === secret) {
+ return "Well done!";
+ } else if (userNumber > secret) {
+ return "Too high!";
+ } else {
+ return "Too low!";
+ }
};
-
- var guess = getGuesser();
-
-
+};
+
+var guess = getGuesser(20);
+console.log(guess(10));
+
+var guessWithOffset = getGuesser(20,5);
+console.log(guessWithOffset(15));
+
/* Further Adventures
*
diff --git a/10_JS_Conditions/Ch10_pgm_07.js b/10_JS_Conditions/Ch10_pgm_07.js
index eb84291..87ddd12 100644
--- a/10_JS_Conditions/Ch10_pgm_07.js
+++ b/10_JS_Conditions/Ch10_pgm_07.js
@@ -1,74 +1,89 @@
// Checking quiz answers
-
var getQuiz = function () {
- var score = 0,
- qIndex = 0,
- inPlay = true,
- questions,
- next,
- getQuestion,
- checkAnswer,
- submit;
-
- questions = [
- {
- question: "What is the highest mountain in the world?",
- answer: "Everest"
- },
- {
- question: "What is the highest mountain in Scotland?",
- answer: "Ben Nevis"
- }
- ];
-
- next = function () {
- qIndex = qIndex + 1;
-
- if (qIndex >= questions.length) {
- inPlay = false;
- console.log("You have finished the quiz.");
- }
- };
-
- getQuestion = function () {
- if (inPlay) {
- return questions[qIndex].question;
- } else {
- return "You have finished the quiz.";
- }
- };
+ var score = 0,
+ qIndex = 0,
+ inPlay = true,
+ quiz,
+ questions,
+ next,
+ getQuestion,
+ checkAnswer,
+ submit,
+ getHint;
- checkAnswer = function (userAnswer) {
- if (userAnswer === questions[qIndex].answer) {
- console.log("Correct!");
- score = score + 1;
- } else {
- console.log("No, the answer is " + questions[qIndex].answer);
- }
- };
-
- submit = function (userAnswer) {
- var message = "You have finished the quiz.";
-
- if (inPlay) {
- checkAnswer(userAnswer);
- next();
- message = "Your score is " + score + " out of " + qIndex;
- }
-
- return message;
- };
+ questions = [
+ {
+ question: "What is the highest mountain in the world?",
+ answer: "Everest",
+ hint: "It is located in the Himalayas."
+ },
+ {
+ question: "What is the highest mountain in Scotland?",
+ answer: "Ben Nevis",
+ hint: "It is part of the Grampian Mountain range."
+ },
+ {
+ question: "What is the capital of India?",
+ answer: "New Delhi",
+ hint: "It is the most popular city in India."
+ }
+ ];
+
+ next = function () {
+ qIndex = qIndex + 1;
- return {
- quizMe: getQuestion,
- submit: submit
- };
+ if (qIndex >= questions.length) {
+ inPlay = false;
+ console.log("You have finished the quiz.");
+ }
};
- var quiz = getQuiz();
+ getQuestion = function () {
+ if (inPlay) {
+ return questions[qIndex].question;
+ } else {
+ return "You have finished the quiz.";
+ }
+ };
+ checkAnswer = function (userAnswer) {
+ if (userAnswer === questions[qIndex].answer) {
+ console.log("Correct!");
+ score = score + 1;
+ } else {
+ console.log("No, the answer is " + questions[qIndex].answer);
+ }
+ };
+ submit = function (userAnswer) {
+ var message = "You have finished the quiz.";
+
+ if (inPlay) {
+ checkAnswer(userAnswer);
+ next();
+ message = "Your score is " + score + " out of " + qIndex;
+ }
+
+ return message;
+ };
+
+ getHint = function () {
+ if (inPlay) {
+ return questions[qIndex].hint;
+ } else {
+ return "You have finished the quiz.";
+ }
+ };
+ return {
+ quizMe: getQuestion,
+ submit: submit,
+ helpMe: getHint
+ };
+};
+
+var quiz = getQuiz();
+
/* Further Adventures
*
* 1) Run the program.
diff --git a/10_JS_Conditions/Ch10_pgm_08.js b/10_JS_Conditions/Ch10_pgm_08.js
index 0ac65f3..05c5623 100644
--- a/10_JS_Conditions/Ch10_pgm_08.js
+++ b/10_JS_Conditions/Ch10_pgm_08.js
@@ -2,242 +2,241 @@
var getGame = function () {
- // The spacer namespace
-
- var spacer = {
- blank: function () {
- return "";
- },
-
- newLine: function () {
- return "\n";
- },
-
- line: function (length, character) {
- var longString = "****************************************";
- longString += "----------------------------------------";
- longString += "========================================";
- longString += "++++++++++++++++++++++++++++++++++++++++";
- longString += " ";
-
- length = Math.max(0, length);
- length = Math.min(40, length);
- return longString.substr(longString.indexOf(character), length);
- },
-
- wrap : function (text, length, character) {
- var padLength = length - text.length - 3;
- var wrapText = character + " " + text;
- wrapText += spacer.line(padLength, " ");
- wrapText += character;
- return wrapText;
- },
-
- box: function (text, length, character) {
- var boxText = spacer.newLine();
- boxText += spacer.line(length, character) + spacer.newLine();
- boxText += spacer.wrap(text, length, character) + spacer.newLine();
- boxText += spacer.line(length, character) + spacer.newLine();
- return boxText;
- }
+ // The spacer namespace
+
+ var spacer = {
+ blank: function () {
+ return "";
+ },
+
+ newLine: function () {
+ return "\n";
+ },
+
+ line: function (length, character) {
+ var longString = "****************************************";
+ longString += "----------------------------------------";
+ longString += "========================================";
+ longString += "++++++++++++++++++++++++++++++++++++++++";
+ longString += " ";
+
+ length = Math.max(0, length);
+ length = Math.min(40, length);
+ return longString.substr(longString.indexOf(character), length);
+ },
+
+ wrap : function (text, length, character) {
+ var padLength = length - text.length - 3;
+ var wrapText = character + " " + text;
+ wrapText += spacer.line(padLength, " ");
+ wrapText += character;
+ return wrapText;
+ },
+
+ box: function (text, length, character) {
+ var boxText = spacer.newLine();
+ boxText += spacer.line(length, character) + spacer.newLine();
+ boxText += spacer.wrap(text, length, character) + spacer.newLine();
+ boxText += spacer.line(length, character) + spacer.newLine();
+ return boxText;
+ }
+ };
+
+
+ // Constructors
+
+ var Player = function (name, health) {
+ var newLine = spacer.newLine();
+ var items = [];
+ var place = null;
+
+ var getNameInfo = function () {
+ return name;
};
-
-
- // Constructors
-
- var Player = function (name, health) {
- var newLine = spacer.newLine();
- var items = [];
- var place = null;
-
- var getNameInfo = function () {
- return name;
- };
-
- var getHealthInfo = function () {
- return "(" + health + ")";
- };
-
- var getItemsInfo = function () {
- var itemsString = "Items:" + newLine;
-
- items.forEach(function (item, i) {
- itemsString += " - " + item + newLine;
- });
-
- return itemsString;
- };
-
- var getTitleInfo = function () {
- return getNameInfo() + " " + getHealthInfo();
- };
-
- var getInfo = function () {
- var info = spacer.box(getTitleInfo(), 40, "*");
- info += " " + getItemsInfo();
- info += spacer.line(40, "*");
- info += newLine;
-
- return info;
- };
-
- this.addItem = function (item) {
- items.push(item);
- };
-
- this.setPlace = function (destination) {
- place = destination;
- };
-
- this.getPlace = function () {
- return place;
- };
-
- this.showInfo = function (character) {
- console.log(getInfo(character));
- };
+
+ var getHealthInfo = function () {
+ return "(" + health + ")";
};
-
- var Place = function (title, description) {
- var newLine = spacer.newLine();
- var items = [];
- var exits = {};
-
- var getItemsInfo = function () {
- var itemsString = "Items: " + newLine;
- items.forEach(function (item) {
- itemsString += " - " + item;
- itemsString += newLine;
- });
- return itemsString;
- };
-
- var getExitsInfo = function () {
- var exitsString = "Exits from " + title;
- exitsString += ":" + newLine;
-
- Object.keys(exits).forEach(function (key) {
- exitsString += " - " + key;
- exitsString += newLine;
- });
-
- return exitsString;
- };
-
- var getTitleInfo = function () {
- return spacer.box(title, title.length + 4, "=");
- };
-
- var getInfo = function () {
- var infoString = getTitleInfo();
- infoString += description;
- infoString += newLine + newLine;
- infoString += getItemsInfo() + newLine;
- infoString += getExitsInfo();
- infoString += spacer.line(40, "=") + newLine;
- return infoString;
- };
-
- this.showInfo = function () {
- console.log(getInfo());
- };
-
- this.addItem = function (item) {
- items.push(item);
- };
-
- this.addExit = function (direction, exit) {
- exits[direction] = exit;
- };
-
- this.getExit = function (direction) {
- return exits[direction];
- };
-
- this.getLastItem = function () {
- return items.pop();
- };
+
+ var getItemsInfo = function () {
+ var itemsString = "Items:" + newLine;
+
+ items.forEach(function (item, i) {
+ itemsString += " - " + item + newLine;
+ });
+
+ return itemsString;
};
-
- // Console update function
- var render = function () {
- console.clear();
- player.getPlace().showInfo();
- player.showInfo();
+
+ var getTitleInfo = function () {
+ return getNameInfo() + " " + getHealthInfo();
};
-
- // Create some places
- var kitchen = new Place(
- "The Kitchen",
- "You are in a kitchen. There is a disturbing smell."
- );
- var library = new Place(
- "The Old Library",
- "You are in a library. Dusty books line the walls."
- );
- var garden = new Place(
- "The Kitchen Garden",
- "You are in a small, walled garden."
- );
- var cupboard = new Place(
- "The Kitchen Cupboard",
- "You are in a cupboard. It's surprisingly roomy."
- );
-
- // Add items and exits to places
- kitchen.addItem("a piece of cheese");
- library.addItem("a rusty key");
- cupboard.addItem("a tin of spam");
-
- kitchen.addExit("south", library);
- kitchen.addExit("west", garden);
- kitchen.addExit("east", cupboard);
-
- library.addExit("north", kitchen);
- garden.addExit("east", kitchen);
- cupboard.addExit("west", kitchen);
-
- // Game initialization
- var player = new Player("Kandra", 50);
- player.addItem("The Sword of Doom");
- player.setPlace(kitchen);
-
- render();
-
- // Return the public interface
- return {
- go: function (direction) {
+
+ var getInfo = function () {
+ var info = spacer.box(getTitleInfo(), 40, "*");
+ info += " " + getItemsInfo();
+ info += spacer.line(40, "*");
+ info += newLine;
+
+ return info;
+ };
+
+ this.addItem = function (item) {
+ items.push(item);
+ };
+
+ this.setPlace = function (destination) {
+ place = destination;
+ };
+
+ this.getPlace = function () {
+ return place;
+ };
+
+ this.showInfo = function (character) {
+ console.log(getInfo(character));
+ };
+ };
+
+ var Place = function (title, description) {
+ var newLine = spacer.newLine();
+ var items = [];
+ var exits = {};
+
+ var getItemsInfo = function () {
+ var itemsString = "Items: " + newLine;
+ items.forEach(function (item) {
+ itemsString += " - " + item;
+ itemsString += newLine;
+ });
+ return itemsString;
+ };
+
+ var getExitsInfo = function () {
+ var exitsString = "Exits from " + title;
+ exitsString += ":" + newLine;
+
+ Object.keys(exits).forEach(function (key) {
+ exitsString += " - " + key;
+ exitsString += newLine;
+ });
+
+ return exitsString;
+ };
+
+ var getTitleInfo = function () {
+ return spacer.box(title, title.length + 4, "=");
+ };
+
+ var getInfo = function () {
+ var infoString = getTitleInfo();
+ infoString += description;
+ infoString += newLine + newLine;
+ infoString += getItemsInfo() + newLine;
+ infoString += getExitsInfo();
+ infoString += spacer.line(40, "=") + newLine;
+ return infoString;
+ };
+
+ this.showInfo = function () {
+ console.log(getInfo());
+ };
+
+ this.addItem = function (item) {
+ items.push(item);
+ };
+
+ this.addExit = function (direction, exit) {
+ exits[direction] = exit;
+ };
+
+ this.getExit = function (direction) {
+ return exits[direction];
+ };
+
+ this.getLastItem = function () {
+ return items.pop();
+ };
+ };
+
+ // Console update function
+ var render = function () {
+ console.clear();
+ player.getPlace().showInfo();
+ player.showInfo();
+ };
+
+ // Create some places
+ var kitchen = new Place(
+ "The Kitchen",
+ "You are in a kitchen. There is a disturbing smell."
+ );
+ var library = new Place(
+ "The Old Library",
+ "You are in a library. Dusty books line the walls."
+ );
+ var garden = new Place(
+ "The Kitchen Garden",
+ "You are in a small, walled garden."
+ );
+ var cupboard = new Place(
+ "The Kitchen Cupboard",
+ "You are in a cupboard. It's surprisingly roomy."
+ );
+
+ // Add items and exits to places
+ kitchen.addItem("a piece of cheese");
+ library.addItem("a rusty key");
+ cupboard.addItem("a tin of spam");
+
+ kitchen.addExit("south", library);
+ kitchen.addExit("west", garden);
+ kitchen.addExit("east", cupboard);
+
+ library.addExit("north", kitchen);
+ garden.addExit("east", kitchen);
+ cupboard.addExit("west", kitchen);
+
+ // Game initialization
+ var player = new Player("Kandra", 50);
+ player.addItem("The Sword of Doom");
+ player.setPlace(kitchen);
+
+ render();
+
+ // Return the public interface
+ return {
+ go: function (direction) {
+ var place = player.getPlace();
+ var destination = place.getExit(direction);
+
+ if (destination !== undefined) {
+ player.setPlace(destination);
+ render();
+ return "";
+ } else {
+ return "*** There is no exit in that direction ***";
+ }
+ },
+
+ get: function () {
var place = player.getPlace();
- var destination = place.getExit(direction);
-
- if (destination !== undefined) {
- player.setPlace(destination);
- render();
- return "";
+ var item = place.getLastItem();
+
+ if (item !== undefined) {
+ player.addItem(item);
+ render();
+ return "";
} else {
- return "*** There is no exit in that direction ***";
+ return "*** There is no item to get ***";
}
- },
-
- get: function () {
- var place = player.getPlace();
- var item = place.getLastItem();
-
- if (item !== undefined) {
- player.addItem(item);
- render();
- return "";
- } else {
- return "*** There is no item to get ***";
- }
- }
- };
-
+ }
};
-
- var game = getGame();
-
-
+
+};
+
+var game = getGame();
+// while going in non-existent directions it shows there is no way there.
/* Further Adventures
*
diff --git a/11_JS_Promises/Ch11_pgm_01.js b/11_JS_Promises/Ch11_pgm_01.js
index a2638f2..a47c8a9 100644
--- a/11_JS_Promises/Ch11_pgm_01.js
+++ b/11_JS_Promises/Ch11_pgm_01.js
@@ -1,20 +1,22 @@
// Callbacks
const doSomething = callback => {
- setTimeout(() => {
- const skills = ['HTML', 'CSS', 'JS']
- callback('It did not go well', skills)
- }, 2000)
- }
-
- const callback = (err, result) => {
- if (err) {
- return console.log(err)
- }
- return console.log(result)
+ setTimeout(() => {
+ const skills = ['HTML', 'CSS', 'JS']
+ callback('It did not go well', skills)
+ }, 5000)
+}
+
+const callback = (err, result) => {
+ if (err) {
+ return console.log(err)
}
-
- doSomething(callback);
+ return console.log(result)
+}
+
+doSomething(callback);
+
+// as i changed to 5000 it displays after 5 secs.
// after 2 seconds it will print
diff --git a/11_JS_Promises/Ch11_pgm_02.js b/11_JS_Promises/Ch11_pgm_02.js
index 8ca3860..cd80cad 100644
--- a/11_JS_Promises/Ch11_pgm_02.js
+++ b/11_JS_Promises/Ch11_pgm_02.js
@@ -3,18 +3,20 @@
// In this case the err is false and it will return the else block which is the result.
const doSomething = callback => {
- setTimeout(() => {
- const skills = ['HTML', 'CSS', 'JS']
- callback(false, skills)
- }, 2000)
+ setTimeout(() => {
+ const skills = ['HTML', 'CSS', 'JS']
+ callback(false, skills)
+ }, 4000)
+}
+
+doSomething((err, result) => {
+ if (err) {
+ return console.log(err)
}
-
- doSomething((err, result) => {
- if (err) {
- return console.log(err)
- }
- return console.log(result)
- })
+ return console.log(result)
+})
+
+//as i changed time to 4000 it displays after 4 secs.
// after 2 seconds it will print the skills
diff --git a/11_JS_Promises/Ch11_pgm_03.js b/11_JS_Promises/Ch11_pgm_03.js
index ae7ae16..4dc1114 100644
--- a/11_JS_Promises/Ch11_pgm_03.js
+++ b/11_JS_Promises/Ch11_pgm_03.js
@@ -9,21 +9,23 @@
// Promise
const doPromise = new Promise((resolve, reject) => {
- setTimeout(() => {
- const skills = ['HTML', 'CSS', 'JS']
- if (skills.length > 0) {
- resolve(skills)
- } else {
- reject('Something wrong has happened')
- }
- }, 2000)
+ setTimeout(() => {
+ const skills = ['HTML', 'CSS', 'JS']
+ if (skills.length > 0) {
+ resolve(skills)
+ } else {
+ reject('Something wrong has happened')
+ }
+ }, 2000)
+})
+
+doPromise
+ .then(result => {
+ console.log(result)
})
-
- doPromise
- .then(result => {
- console.log(result)
- })
- .catch(error => console.log(error))
+ .catch(error => console.log(error))
+
+ //when I delete the array element it display after 2 secs as something went wrong shown in the else part.
diff --git a/11_JS_Promises/Ch11_pgm_04.js b/11_JS_Promises/Ch11_pgm_04.js
index 263de4f..0407f2f 100644
--- a/11_JS_Promises/Ch11_pgm_04.js
+++ b/11_JS_Promises/Ch11_pgm_04.js
@@ -2,22 +2,24 @@
// Promise
const doPromise = new Promise((resolve, reject) => {
- setTimeout(() => {
- const skills = ['HTML', 'CSS', 'JS']
- if (skills.includes('Node')) {
- resolve('fullstack developer')
- } else {
- reject('Something wrong has happened')
- }
- }, 2000)
+ setTimeout(() => {
+ const skills = ['HTML', 'CSS', 'JS', 'Node']
+ if (skills.includes('Node')) {
+ resolve('fullstack developer')
+ } else {
+ reject('Something wrong has happened')
+ }
+ }, 2000)
+})
+
+doPromise
+ .then(result => {
+ console.log(result)
})
-
- doPromise
- .then(result => {
- console.log(result)
- })
- .catch(error => console.error(error))
+ .catch(error => console.error(error))
+ //as the node element is not added to the array it shows the else part.
+ // after adding Node it displays the if part.
// Something wrong has happened
\ No newline at end of file
diff --git a/11_JS_Promises/Ch11_pgm_05.js b/11_JS_Promises/Ch11_pgm_05.js
index 361d886..577b1b2 100644
--- a/11_JS_Promises/Ch11_pgm_05.js
+++ b/11_JS_Promises/Ch11_pgm_05.js
@@ -1,5 +1,27 @@
const countriesAPI = 'https://restcountries.com/v2/all'
const catsAPI = 'https://api.thecatapi.com/v1/breeds'
+fetch(countriesAPI)
+.then(response => {
+ if(!response.ok){
+ throw new console.error('Network response was not ok' + response.statusText);
+ }
+ return response.json();
+})
+.then(data => {
+ data.forEach(country => {
+ const{ name, capital, languages, population, area } = country;
+ console.log(`country: ${name}`);
+ console.log(`capital: ${capital}`);
+ console.log(`Languages: ${languages.map(lang => lang.name).join(', ')}`);
+ console.log(`Population: ${population}`);
+ console.log(`Area: ${area}`);
+ console.log(`----------------------------`)
+ });
+
+})
+.catch(error => {
+ console.log("There has been a problem with your fetch operation:", error);
+});
// Read the countries API using fetch and print the name of country, capital, languages,
// population and area.
\ No newline at end of file
diff --git a/11_JS_Promises/Ch11_pgm_06.js b/11_JS_Promises/Ch11_pgm_06.js
index 925337d..e7c2083 100644
--- a/11_JS_Promises/Ch11_pgm_06.js
+++ b/11_JS_Promises/Ch11_pgm_06.js
@@ -1,4 +1,24 @@
const countriesAPI = 'https://restcountries.com/v2/all'
const catsAPI = 'https://api.thecatapi.com/v1/breeds'
+fetch(catsAPI)
+.then(response => {
+ if(!response.ok){
+ throw new console.error('Network response was not ok' + response.statusText);
+ }
+ return response.json();
+
+})
+.then(data => {
+ data.forEach(cat =>{
+ const{ name, temperament, origin} = cat;
+ console.log(`cat name: ${name}`);
+ console.log(`temperament: ${temperament}`);
+ console.log(`origin: ${origin}`);
+ console.log(`----------------------------`);
+ });
+})
+.catch(error =>{
+ console.log("There has been a problem with your fetch operation:", error);
+});
// Print out all the cat names in to catNames variable.
\ No newline at end of file
diff --git a/11_JS_Promises/Ch11_pgm_07.js b/11_JS_Promises/Ch11_pgm_07.js
index 249ea81..7131159 100644
--- a/11_JS_Promises/Ch11_pgm_07.js
+++ b/11_JS_Promises/Ch11_pgm_07.js
@@ -1,6 +1,56 @@
-const countriesAPI = 'https://restcountries.com/v2/all'
-const catsAPI = 'https://api.thecatapi.com/v1/breeds'
+const countriesAPI = 'https://restcountries.com/v2/all';
+const catsAPI = 'https://api.thecatapi.com/v1/breeds';
+// Fetch data from the cats API and calculate the average weight of cats in metric units
+fetch(catsAPI)
+ .then(response => response.json())
+ .then(data => {
+ let totalWeight = 0;
+ let count = 0;
+
+ data.forEach(cat => {
+ const weightMetric = cat.weight.metric; // e.g., "3 - 5"
+ const weights = weightMetric.split(' - ').map(Number); // Convert to [3, 5]
+ const averageWeight = (weights[0] + weights[1]) / 2; // Calculate average
+ totalWeight += averageWeight;
+ count++;
+ });
+
+ const averageWeightOfCats = totalWeight / count;
+ console.log(`Average weight of cats (in metric units): ${averageWeightOfCats.toFixed(2)} kg`);
+ })
+ .catch(error => console.error('Error fetching cat data:', error));
+
+// Fetch data from the countries API to find the 10 largest countries by area
+fetch(countriesAPI)
+ .then(response => response.json())
+ .then(data => {
+ const sortedCountries = data.sort((a, b) => b.area - a.area); // Sort by area in descending order
+ const largestCountries = sortedCountries.slice(0, 10); // Get top 10 largest countries
+
+ console.log('10 largest countries by area:');
+ largestCountries.forEach(country => {
+ console.log(`${country.name}: ${country.area} sq km`);
+ });
+ })
+ .catch(error => console.error('Error fetching country data:', error));
+
+// Fetch data from the countries API to count the total number of official languages
+fetch(countriesAPI)
+ .then(response => response.json())
+ .then(data => {
+ const languagesSet = new Set();
+
+ data.forEach(country => {
+ country.languages.forEach(language => {
+ languagesSet.add(language.name);
+ });
+ });
+
+ const totalLanguages = languagesSet.size;
+ console.log(`Total number of official languages in the world: ${totalLanguages}`);
+ })
+ .catch(error => console.error('Error fetching country data:', error));
// Read the cats api and find the average weight of cat in metric unit.
// Read the countries api and find out the 10 largest countries
// Read the countries api and count total number of languages in the world used as officials.
\ No newline at end of file
diff --git a/11_JS_Promises/async_await.js b/11_JS_Promises/async_await.js
index 076a125..f0730e1 100644
--- a/11_JS_Promises/async_await.js
+++ b/11_JS_Promises/async_await.js
@@ -17,38 +17,33 @@
// To access the value from the promise, we will use the keyword await.
-const square = async function (n) {
- return n * n
- }
- const value = await square(2)
- console.log(value)
-
-// 4
-
-
-// Let us fetch API data using both promise method and async and await method.
-
-// promise
const url = 'https://restcountries.com/v2/all'
-fetch(url)
- .then(response => response.json())
- .then(data => {
- console.log(data)
- })
- .catch(error => console.error(error))
-
-
-// async and await
-
-const fetchData = async () => {
- try {
- const response = await fetch(url)
- const countries = await response.json()
- console.log(countries)
- } catch (err) {
- console.error(err)
+ fetch(url)
+ .then(response => response.json())
+ .then(data => {
+ console.log(data)
+ })
+ .catch(error => console.error(error))
+
+
+ // async and await
+
+ const fetchData = async () => {
+ try {
+ const response = await fetch(url)
+ const countries = await response.json()
+ console.log(countries)
+ } catch (err) {
+ console.error(err)
+ }
}
- }
- console.log('===== async and await')
- fetchData()
\ No newline at end of file
+ console.log('===== async and await')
+ fetchData()
+
+const square = async function (n) {
+ return n * n
+ };
+ square(2)
+ .then(value => console.log(value))
+ .catch(error => console.error(error));
\ No newline at end of file
diff --git a/11_JS_Promises/fetchAPI.js b/11_JS_Promises/fetchAPI.js
index 5f7354d..356b3d6 100644
--- a/11_JS_Promises/fetchAPI.js
+++ b/11_JS_Promises/fetchAPI.js
@@ -11,4 +11,34 @@ fetch(url)
// getting the data
console.log(data)
})
- .catch(error => console.error(error)) // handling error if something wrong happens
\ No newline at end of file
+ .catch(error => console.error('Fetch error:', error)); // Handling error if something goes wrong
+
+// Using async and await
+const fetchData = async () => {
+ try {
+ const response = await fetch(url);
+ // Checking if the response is successful
+ if (!response.ok) {
+ throw new Error('Network response was not ok ' + response.statusText);
+ }
+ const countries = await response.json();
+
+ // Getting and processing the data
+ console.log(countries);
+ } catch (err) {
+ console.error('Fetch error:', err);
+ }
+};
+
+console.log('===== async and await =====');
+fetchData();
+
+// Async function to square a number
+const square = async function (n) {
+ return n * n;
+};
+
+// Using the async function and handling the promise
+square(2)
+ .then(value => console.log(`Square of 2: ${value}`))
+ .catch(error => console.error('Error:', error));
\ No newline at end of file
diff --git a/12_JS_Sets_Maps/Ch12_pgm_01.js b/12_JS_Sets_Maps/Ch12_pgm_01.js
index 094e09c..f2a4ca4 100644
--- a/12_JS_Sets_Maps/Ch12_pgm_01.js
+++ b/12_JS_Sets_Maps/Ch12_pgm_01.js
@@ -2,6 +2,33 @@ const a = [4, 5, 8, 9]
const b = [3, 4, 5, 7]
const countries = ['Finland', 'Sweden', 'Norway']
+const c = []
+console.log("Empty set c:", c);
+
+
+const numSet = new Set();
+for(let i = 0; i <= 10; i++){
+ numSet.add(i);
+}
+console.log("Number Set:", numSet);
+
+numSet.delete(5);
+console.log("After deleting", numSet);
+
+numSet.clear();
+console.log("After clearing:", numSet);
+
+const birds = ["peacock", "crow", "dove", "parrot", "swan"]
+console.log("Set of 5 string elements:", birds);
+
+const countryMap = new Map();
+countries.forEach(country => {
+ countryMap.set(country, country.length);
+});
+console.log("Map of countries and number of characters:");
+countryMap.forEach((value, key)=> {
+ console.log(`${key}: ${value}`);
+});
// create an empty set
// Create a set containing 0 to 10 using loop
diff --git a/12_JS_Sets_Maps/Ch12_pgm_02.js b/12_JS_Sets_Maps/Ch12_pgm_02.js
index a8111d7..1efc0c6 100644
--- a/12_JS_Sets_Maps/Ch12_pgm_02.js
+++ b/12_JS_Sets_Maps/Ch12_pgm_02.js
@@ -1,7 +1,21 @@
-const a = [4, 5, 8, 9]
-const b = [3, 4, 5, 7]
+const a = [4, 5, 8, 9];
+const b = [3, 4, 5, 7];
const countries = ['Finland', 'Sweden', 'Norway']
+const setA = new Set(a);
+const setB = new Set(b);
+
+// Find union of a and b
+const unionSet = new Set([...setA, ...setB]);
+console.log('Union of a and b:', [...unionSet]);
+
+// Find intersection of a and b
+const intersectionSet = new Set([...setA].filter(item => setB.has(item)));
+console.log('Intersection of a and b:', [...intersectionSet]);
+
+// Find difference of a and b
+const differenceSet = new Set([...setA].filter(item => !setB.has(item)));
+console.log('Difference of a and b:', [...differenceSet]);
// Find a union b
// Find a intersection b
// Find a with b
\ No newline at end of file
diff --git a/12_JS_Sets_Maps/Ch12_pgm_03.js b/12_JS_Sets_Maps/Ch12_pgm_03.js
index a223b63..543be0a 100644
--- a/12_JS_Sets_Maps/Ch12_pgm_03.js
+++ b/12_JS_Sets_Maps/Ch12_pgm_03.js
@@ -2,6 +2,42 @@ const a = [4, 5, 8, 9]
const b = [3, 4, 5, 7]
const countries = ['Finland', 'Sweden', 'Norway']
+const url = 'https://restcountries.com/v2/all';
+
+// Function to fetch countries data and count languages
+const fetchCountriesData = async () => {
+ try {
+ const response = await fetch(url);
+ const countries = await response.json();
+
+ const languageCounts = countries.reduce((acc, country) => {
+ country.languages.forEach(language => {
+ acc[language.name] = (acc[language.name] || 0) + 1;
+ });
+ return acc;
+ }, {});
+
+ return languageCounts;
+ } catch (err) {
+ console.error('Fetch error:', err);
+ }
+};
+
+
+const mostSpokenLanguages = async (countries, topN) => {
+ const languageCounts = await fetchCountriesData();
+
+ const sortedLanguages = Object.entries(languageCounts)
+ .map(([language, count]) => ({ [language]: count }))
+ .sort((a, b) => Object.values(b)[0] - Object.values(a)[0])
+ .slice(0, topN);
+
+ return sortedLanguages;
+};
+
+mostSpokenLanguages(countries, 10).then(result => console.log(result));
+
+mostSpokenLanguages(countries, 3).then(result => console.log(result));
// How many languages are there in the countries object file.
// *** Use the countries data to find the 10 most spoken languages:
diff --git a/13_JS_DOM/Ch13_pgm_01.js b/13_JS_DOM/Ch13_pgm_01.js
deleted file mode 100644
index ab193db..0000000
--- a/13_JS_DOM/Ch13_pgm_01.js
+++ /dev/null
@@ -1,14 +0,0 @@
-// 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
-// 2. Get each of the the paragraph using document.querySelector('#id') and by their id
-// 3. Get all the p as nodeList using document.querySelectorAll(tagname) and by their tag name
-// 4. Loop through the nodeList and get the text content of each paragraph
-// 5. Set a text content to paragraph the fourth paragraph,Fourth Paragraph
-// 6. Set id and class attribute for all the paragraphs using different attribute setting methods
-
-// Level 2
-
-// 1. Change stye of each paragraph using JavaScript(eg. color, background, border, font-size, font-family)
-// 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
-// 3. Set text content, id and class to each paragraph
\ No newline at end of file
diff --git a/13_JS_DOM/Ch13_pgm_02.js b/13_JS_DOM/Ch13_pgm_02.js
deleted file mode 100644
index 913927e..0000000
--- a/13_JS_DOM/Ch13_pgm_02.js
+++ /dev/null
@@ -1,36 +0,0 @@
-// DOM: Mini Project
-
-// 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.
-
-// 1. The year color is changing every 1 second
-// 2. The date and time background color is changing every on seconds
-// 3. Completed challenge has background green
-// 4. Ongoing challenge has background yellow
-// 5. Coming challenges have background red
-
-
-
-//
-
-
-//
-//
-//
-// JavaScript for Everyone:DOM
-//
-//
-//
-//
JavaScript Challenges in 2024
-//
30DaysOfJavaScript Challenge
-//
-//
30DaysOfPython Challenge Done
-//
30DaysOfJavaScript Challenge Ongoing
-//
30DaysOfReact Challenge Coming
-//
30DaysOfFullStack Challenge Coming
-//
30DaysOfDataAnalysis Challenge Coming
-//
30DaysOfReactNative Challenge Coming
-//
30DaysOfMachineLearning Challenge Coming
-//
-//
-//
-//
\ No newline at end of file
diff --git a/13_JS_DOM/Ch13_pro_01/Ch13_pro_01.HTML b/13_JS_DOM/Ch13_pro_01/Ch13_pro_01.HTML
new file mode 100644
index 0000000..3b5af59
--- /dev/null
+++ b/13_JS_DOM/Ch13_pro_01/Ch13_pro_01.HTML
@@ -0,0 +1,16 @@
+
+
+
+
+
+ Document
+
+
+
Lorem ipsum dolor sit amet.
+
Lorem ipsum dolor, sit amet consectetur adipisicing.
+
Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa, deleniti?
+
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Consectetur et distinctio dolorem. Repellat, accusantium cum!
+
+
+
\ No newline at end of file
diff --git a/13_JS_DOM/Ch13_pro_01/Ch13_pro_01.js b/13_JS_DOM/Ch13_pro_01/Ch13_pro_01.js
new file mode 100644
index 0000000..e824e47
--- /dev/null
+++ b/13_JS_DOM/Ch13_pro_01/Ch13_pro_01.js
@@ -0,0 +1,77 @@
+// Get the first paragraph
+const firstParagraph = document.querySelector("p");
+console.log(firstParagraph);
+
+// Get each of the paragraphs by their id
+const para1 = document.querySelector("#para1");
+const para2 = document.querySelector("#para2");
+const para3 = document.querySelector("#para3");
+const para4 = document.querySelector("#para4");
+
+console.log(para1, para2, para3, para4);
+
+// Get all the p elements as a NodeList
+const paragraphs = document.querySelectorAll("p");
+console.log(paragraphs);
+
+// Loop through the NodeList and get the text content of each paragraph
+paragraphs.forEach(paragraph => {
+ console.log(paragraph.textContent);
+});
+
+
+para4.textContent = 'Lorem ipsum dolor sit amet consectetur, adipisicing elit. Consectetur et distinctio dolorem. Repellat, accusantium cum!';
+
+// Set id and class attribute for all the paragraphs using different methods
+paragraphs[0].setAttribute("id", "id1");
+paragraphs[0].setAttribute("class", "first");
+
+paragraphs[1].id = "id2";
+paragraphs[1].className = "second";
+
+paragraphs[2].id = "id3";
+paragraphs[2].classList.add("third");
+
+paragraphs[3].id = "id4";
+paragraphs[3].classList.add("fourth");
+
+// Change style of each paragraph
+paragraphs[0].style.color = 'blue';
+paragraphs[0].style.backgroundColor = 'lightgray';
+paragraphs[0].style.border = '1px solid black';
+paragraphs[0].style.fontSize = '20px';
+paragraphs[0].style.fontFamily = 'Arial';
+
+paragraphs[1].style.color = 'blue';
+paragraphs[1].style.backgroundColor = 'lightgray';
+paragraphs[1].style.border = '1px solid black';
+paragraphs[1].style.fontSize = '20px';
+paragraphs[1].style.fontFamily = 'Arial';
+
+paragraphs[2].style.color = 'blue';
+paragraphs[2].style.backgroundColor = 'lightgray';
+paragraphs[2].style.border = '1px solid black';
+paragraphs[2].style.fontSize = '20px';
+paragraphs[2].style.fontFamily = 'Arial';
+
+paragraphs[3].style.color = 'blue';
+paragraphs[3].style.backgroundColor = 'lightgray';
+paragraphs[3].style.border = '1px solid black';
+paragraphs[3].style.fontSize = '20px';
+paragraphs[3].style.fontFamily = 'Arial';
+
+// Loop through each paragraph to set color
+paragraphs.forEach((paragraph, index) => {
+ if (index % 2 === 0) { // First and Third Paragraph (0 and 2 index)
+ paragraph.style.color = 'green';
+ } else { // Second and Fourth Paragraph (1 and 3 index)
+ paragraph.style.color = 'red';
+ }
+});
+
+// Set text content, id, and class to each paragraph
+paragraphs.forEach((paragraph, index) => {
+ paragraph.textContent = `Paragraph ${index + 1}`;
+ paragraph.id = `newId${index + 1}`;
+ paragraph.className = `newClass${index + 1}`;
+});
\ No newline at end of file
diff --git a/13_JS_DOM/Ch13_pro_02/Ch13_pro_02.html b/13_JS_DOM/Ch13_pro_02/Ch13_pro_02.html
new file mode 100644
index 0000000..4bcb3c1
--- /dev/null
+++ b/13_JS_DOM/Ch13_pro_02/Ch13_pro_02.html
@@ -0,0 +1,64 @@
+
+
+
+ JavaScript for Everyone:DOM
+
+
+
+
+
+
JavaScript Challenges in 2024
+
30DaysOfJavaScript Challenge
+
+
30DaysOfPython Challenge Done
+
30DaysOfJavaScript Challenge Ongoing
+
30DaysOfReact Challenge Coming
+
30DaysOfFullStack Challenge Coming
+
30DaysOfDataAnalysis Challenge Coming
+
30DaysOfReactNative Challenge Coming
+
30DaysOfMachineLearning Challenge Coming
+
+
+
+
+
\ No newline at end of file
diff --git a/13_JS_DOM/Ch13_pro_02/Ch13_pro_02.js b/13_JS_DOM/Ch13_pro_02/Ch13_pro_02.js
new file mode 100644
index 0000000..25c40d7
--- /dev/null
+++ b/13_JS_DOM/Ch13_pro_02/Ch13_pro_02.js
@@ -0,0 +1,31 @@
+
+function changeYearColor() {
+ const yearHeader = document.querySelector('h1');
+ setInterval(() => {
+ const randomColor = getRandomColor();
+ yearHeader.style.color = randomColor;
+ }, 1000);
+ }
+
+
+ function changeDateTimeBackground() {
+ const dateTimeSection = document.querySelector('.wrapper');
+ setInterval(() => {
+ const randomColor = getRandomColor();
+ dateTimeSection.style.backgroundColor = randomColor;
+ }, 1000);
+ }
+
+
+ function getRandomColor() {
+ const letters = '0123456789ABCDEF';
+ let color = '#';
+ for (let i = 0; i < 6; i++) {
+ color += letters[Math.floor(Math.random() * 16)];
+ }
+ return color;
+ }
+
+ changeYearColor();
+ changeDateTimeBackground();
+
\ No newline at end of file
diff --git a/14_JS_MANUPLATING_DOM_OBJECT/Ch14_pro_01/Ch14_pro_01.html b/14_JS_MANUPLATING_DOM_OBJECT/Ch14_pro_01/Ch14_pro_01.html
new file mode 100644
index 0000000..1732769
--- /dev/null
+++ b/14_JS_MANUPLATING_DOM_OBJECT/Ch14_pro_01/Ch14_pro_01.html
@@ -0,0 +1,32 @@
+
+
+
+
+
+Document
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/14_JS_MANUPLATING_DOM_OBJECT/Ch14_pro_01/Ch14_pro_01.js b/14_JS_MANUPLATING_DOM_OBJECT/Ch14_pro_01/Ch14_pro_01.js
new file mode 100644
index 0000000..fa07c12
--- /dev/null
+++ b/14_JS_MANUPLATING_DOM_OBJECT/Ch14_pro_01/Ch14_pro_01.js
@@ -0,0 +1,32 @@
+function isPrime(num) {
+ if (num <= 1) return false;
+ if (num === 2) return true;
+ if (num % 2 === 0) return false;
+ for (let i = 3; i <= Math.sqrt(num); i += 2) {
+ if (num % i === 0) return false;
+ }
+ return true;
+}
+
+
+const container = document.getElementById('number-container');
+
+
+for (let i = 1; i <= 100; i++) {
+ const numberDiv = document.createElement('div');
+ numberDiv.textContent = i;
+ numberDiv.classList.add('number');
+
+ if (i % 2 === 0) {
+ numberDiv.classList.add('even');
+ } else {
+ numberDiv.classList.add('odd');
+ }
+
+
+ if (isPrime(i)) {
+ numberDiv.classList.add('prime');
+ }
+
+ container.appendChild(numberDiv);
+}
\ No newline at end of file
diff --git a/14_JS_MANUPLATING_DOM_OBJECT/Ch14_pro_02/Ch14_pro_02.html b/14_JS_MANUPLATING_DOM_OBJECT/Ch14_pro_02/Ch14_pro_02.html
new file mode 100644
index 0000000..9db560c
--- /dev/null
+++ b/14_JS_MANUPLATING_DOM_OBJECT/Ch14_pro_02/Ch14_pro_02.html
@@ -0,0 +1,56 @@
+
+
+
+
+
+Document
+
+
+
+
+
List of Countries
+
+
+
+
+
+
\ No newline at end of file
diff --git a/14_JS_MANUPLATING_DOM_OBJECT/Ch14_pro_02/Ch14_pro_02.js b/14_JS_MANUPLATING_DOM_OBJECT/Ch14_pro_02/Ch14_pro_02.js
new file mode 100644
index 0000000..abd936f
--- /dev/null
+++ b/14_JS_MANUPLATING_DOM_OBJECT/Ch14_pro_02/Ch14_pro_02.js
@@ -0,0 +1,10 @@
+const countries = ['Afghanistan','Bangladesh', 'Barbados', 'Belarus', 'Belgium','Sri Lanka', 'Sudan', 'Suriname', 'Sweden', 'Switzerland', 'Syria', 'Taiwan', 'India'];
+
+const countriesList = document.getElementById('countries-list');
+
+// Loop through the countries array and create list items for each country
+countries.forEach(country => {
+ const li = document.createElement('li');
+ li.textContent = country;
+ countriesList.appendChild(li);
+});
\ No newline at end of file
diff --git a/14_JS_Manipulating_DOM_object/Ch14_pgm_01.js b/14_JS_Manipulating_DOM_object/Ch14_pgm_01.js
deleted file mode 100644
index ed728c9..0000000
--- a/14_JS_Manipulating_DOM_object/Ch14_pgm_01.js
+++ /dev/null
@@ -1,5 +0,0 @@
-// Create a div container on HTML document and create 100 to 100 numbers dynamically and append to the container div.
-
-// 1. Even numbers background is green
-// 2. Odd numbers background is yellow
-// 3. Prime numbers background is red
\ No newline at end of file
diff --git a/14_JS_Manipulating_DOM_object/Ch14_pgm_02.js b/14_JS_Manipulating_DOM_object/Ch14_pgm_02.js
deleted file mode 100644
index d8eef10..0000000
--- a/14_JS_Manipulating_DOM_object/Ch14_pgm_02.js
+++ /dev/null
@@ -1,6 +0,0 @@
-// Use the countries array to display all the countries.
-
-
-//See the design
-
-// https://github.com/Asabeneh/30-Days-Of-JavaScript/raw/master/images/projects/dom_min_project_countries_aray_day_2.2.png
\ No newline at end of file
diff --git a/15_JS_EVENT_LISTENERS/Ch15_pro_01/Ch15_pro_01.html b/15_JS_EVENT_LISTENERS/Ch15_pro_01/Ch15_pro_01.html
new file mode 100644
index 0000000..8ba81d7
--- /dev/null
+++ b/15_JS_EVENT_LISTENERS/Ch15_pro_01/Ch15_pro_01.html
@@ -0,0 +1,44 @@
+
+
+
+
+
+Document
+
+
+
+
Even = Green
+
Prime = Red
+
Odd = Yellow
+
+
+
+
+
\ No newline at end of file
diff --git a/15_JS_EVENT_LISTENERS/Ch15_pro_01/Ch15_pro_01.js b/15_JS_EVENT_LISTENERS/Ch15_pro_01/Ch15_pro_01.js
new file mode 100644
index 0000000..50d8285
--- /dev/null
+++ b/15_JS_EVENT_LISTENERS/Ch15_pro_01/Ch15_pro_01.js
@@ -0,0 +1,32 @@
+function isPrime(num) {
+ if (num <= 1) return false;
+ if (num === 2) return true;
+ if (num % 2 === 0) return false;
+ for (let i = 3; i <= Math.sqrt(num); i += 2) {
+ if (num % i === 0) return false;
+ }
+ return true;
+}
+
+
+const container = document.getElementById('number-container');
+
+
+for (let i = 1; i <= 50; i++) {
+ const numberDiv = document.createElement('div');
+ numberDiv.textContent = i;
+ numberDiv.classList.add('number');
+
+
+ if (i % 2 === 0) {
+ numberDiv.classList.add('even');
+ } else {
+ numberDiv.classList.add('odd');
+ }
+
+ if (isPrime(i)) {
+ numberDiv.classList.add('prime');
+ }
+
+ container.appendChild(numberDiv);
+}
\ No newline at end of file
diff --git a/15_JS_EVENT_LISTENERS/Ch15_pro_02/Ch15_pro_02.html b/15_JS_EVENT_LISTENERS/Ch15_pro_02/Ch15_pro_02.html
new file mode 100644
index 0000000..78bb6ed
--- /dev/null
+++ b/15_JS_EVENT_LISTENERS/Ch15_pro_02/Ch15_pro_02.html
@@ -0,0 +1,51 @@
+
+
+
+
+
+Keyboard Key Code Display
+
+
+
+
+
Keyboard Key Code Display
+
Press any key to display its code
+
+
+
+
+
\ No newline at end of file
diff --git a/15_JS_EVENT_LISTENERS/Ch15_pro_02/Ch15_pro_02.js b/15_JS_EVENT_LISTENERS/Ch15_pro_02/Ch15_pro_02.js
new file mode 100644
index 0000000..b500d1a
--- /dev/null
+++ b/15_JS_EVENT_LISTENERS/Ch15_pro_02/Ch15_pro_02.js
@@ -0,0 +1,7 @@
+// Select the element where the key code will be displayed
+const keyDisplay = document.getElementById('key-display');
+
+// Add event listener to capture key presses
+document.addEventListener('keydown', event => {
+ keyDisplay.textContent = `Key Code: ${event.keyCode}`;
+});
\ No newline at end of file
diff --git a/15_JS_Event_listeners/Ch15_pgm_01.js b/15_JS_Event_listeners/Ch15_pgm_01.js
deleted file mode 100644
index 5f7155a..0000000
--- a/15_JS_Event_listeners/Ch15_pgm_01.js
+++ /dev/null
@@ -1,5 +0,0 @@
-// Generating numbers and marking evens, odds and prime numbers with three different colors.
-
-// See the image below.
-
-// https://github.com/Asabeneh/30-Days-Of-JavaScript/raw/master/images/projects/dom_min_project_number_generator_day_3.1.gif
\ No newline at end of file
diff --git a/15_JS_Event_listeners/Ch15_pgm_02.js b/15_JS_Event_listeners/Ch15_pgm_02.js
deleted file mode 100644
index 90f6ddf..0000000
--- a/15_JS_Event_listeners/Ch15_pgm_02.js
+++ /dev/null
@@ -1,6 +0,0 @@
-// Generating the keyboard code code using even listener.
-
-// The image below.
-
-// https://github.com/Asabeneh/30-Days-Of-JavaScript/raw/master/images/projects/dom_min_project_keycode_day_3.2.gif
-
diff --git a/16_JS_CLOSURES/Ch16_pro_01.js b/16_JS_CLOSURES/Ch16_pro_01.js
new file mode 100644
index 0000000..b3d9739
--- /dev/null
+++ b/16_JS_CLOSURES/Ch16_pro_01.js
@@ -0,0 +1,92 @@
+function createClosureExample1() {
+ let outerVar = 'I am outer';
+
+ function innerFunction() {
+ console.log(`Inner function accessing outer variable: ${outerVar}`);
+ }
+
+ return innerFunction;
+}
+
+const innerFunc = createClosureExample1();
+innerFunc();
+
+
+function createClosureExample2() {
+ let count = 0;
+
+ function increment() {
+ count++;
+ console.log(`Count incremented: ${count}`);
+ }
+
+ function decrement() {
+ count--;
+ console.log(`Count decremented: ${count}`);
+ }
+
+ function getCount() {
+ console.log(`Current count: ${count}`);
+ }
+
+ return { increment, decrement, getCount };
+}
+
+const counter = createClosureExample2();
+counter.increment();
+counter.increment();
+counter.decrement();
+counter.getCount();
+
+
+function createPersonAccount(firstName, lastName) {
+ let incomes = [];
+ let expenses = [];
+
+ function addIncome(description, amount) {
+ incomes.push({ description, amount });
+ }
+
+ function addExpense(description, amount) {
+ expenses.push({ description, amount });
+ }
+
+ function totalIncome() {
+ let total = 0;
+ incomes.forEach(item => {
+ total += item.amount;
+ });
+ return total;
+ }
+
+ function totalExpense() {
+ let total = 0;
+ expenses.forEach(item => {
+ total += item.amount;
+ });
+ return total;
+ }
+
+ function accountInfo() {
+ return `${firstName} ${lastName}'s account:\nTotal Income: ${totalIncome()}\nTotal Expense: ${totalExpense()}`;
+ }
+
+ function accountBalance() {
+ return totalIncome() - totalExpense();
+ }
+
+ return { addIncome, addExpense, accountInfo, accountBalance };
+}
+
+
+const anandKumarAccount = createPersonAccount('Anand', 'Kumar');
+anandKumarAccount.addIncome('Salary', 3000);
+anandKumarAccount.addIncome('Petrol', 1000);
+anandKumarAccount.addExpense('Rent', 1200);
+anandKumarAccount.addExpense('Food', 300);
+
+console.log(anandKumarAccount.accountInfo());
+
+
+
+console.log(`Current Balance: ${anandKumarAccount.accountBalance()}`);
diff --git a/16_JS_Closures/Ch16_pgm_01.js b/16_JS_Closures/Ch16_pgm_01.js
deleted file mode 100644
index a2fc1ea..0000000
--- a/16_JS_Closures/Ch16_pgm_01.js
+++ /dev/null
@@ -1,14 +0,0 @@
-// Level 1
-
-// Create a closure which has one inner function
-
-// Level 2
-
-// Create a closure which has three inner functions
-
-// Level 3
-
-// 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.
\ No newline at end of file
diff --git a/16_JS_Closures/closures.md b/16_JS_Closures/closures.md
deleted file mode 100644
index 4bf6f13..0000000
--- a/16_JS_Closures/closures.md
+++ /dev/null
@@ -1,56 +0,0 @@
-# Closure
-
-JavaScript allows writing function inside an outer function. We can write as many inner functions as we want. If inner function access the variables of outer function then it is called closure.
-
-```
-function outerFunction() {
- let count = 0;
- function innerFunction() {
- count++
- return count
- }
-
- return innerFunction
-}
-const innerFunc = outerFunction()
-
-console.log(innerFunc())
-console.log(innerFunc())
-console.log(innerFunc())
-```
-
-```
-1
-2
-3
-```
-
-#### Let us more example of inner functions
-
-```
-function outerFunction() {
- let count = 0;
- function plusOne() {
- count++
- return count
- }
- function minusOne() {
- count--
- return count
- }
-
- return {
- plusOne:plusOne(),
- minusOne:minusOne()
- }
-}
-const innerFuncs = outerFunction()
-
-console.log(innerFuncs.plusOne)
-console.log(innerFuncs.minusOne)
-```
-
-```
-1
-0
-```
\ No newline at end of file
diff --git a/17_JSON/json.md b/17_JSON/json.md
deleted file mode 100644
index a78f34a..0000000
--- a/17_JSON/json.md
+++ /dev/null
@@ -1,427 +0,0 @@
-# JSON
-
-JSON stands for JavaScript Object Notation. The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text or string only. JSON is a light weight data format for storing and transporting. JSON is mostly used when data is sent from a server to a client. JSON is an easier-to-use alternative to XML.
-
-**Example:**
-
-```
-{
-"users":[
- {
- "firstName":"Asabeneh",
- "lastName":"Yetayeh",
- "age":250,
- "email":"asab@asb.com"
- },
- {
- "firstName":"Alex",
- "lastName":"James",
- "age":25,
- "email":"alex@alex.com"
- },
- {
- "firstName":"Lidiya",
- "lastName":"Tekle",
- "age":28,
- "email":"lidiya@lidiya.com"
- }
-]
-}
-```
-
-The above JSON example is not much different from a normal object. Then, what is the difference ? The difference is the key of a JSON object should be with double quotes or it should be a string. JavaScript Object and JSON are very similar that we can change JSON to Object and Object to JSON.
-
-Let us see the above example in more detail, it starts with a curly bracket. Inside the curly bracket, there is "users" key which has a value array. Inside the array we have different objects and each objects has keys, each keys has to have double quotes. For instance, we use "firstNaMe" instead of just firstName, however in object we use keys without double quotes. This is the major difference between an object and a JSON. Let's see more examples about JSON.
-
-**Example:**
-
-```
-{
- "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
- }
-}
-```
-
-## Converting JSON to JavaScript Object
-
-Mostly we fetch JSON data from HTTP response or from a file, but we can store the JSON as a string and we can change to Object for sake of demonstration. In JavaScript the keyword JSON has parse() and stringify() methods. When we want to change the JSON to an object we parse the JSON using JSON.parse(). When we want to change the object to JSON we use JSON.stringify().
-
-### JSON.parse()
-
-```
-JSON.parse(json[, reviver])
-// json or text , the data
-// reviver is an optional callback function
-/* JSON.parse(json, (key, value) => {
-
-})
-*/
-```
-```
-const usersText = `{
-"users":[
- {
- "firstName":"Asabeneh",
- "lastName":"Yetayeh",
- "age":250,
- "email":"asab@asb.com"
- },
- {
- "firstName":"Alex",
- "lastName":"James",
- "age":25,
- "email":"alex@alex.com"
- },
- {
- "firstName":"Lidiya",
- "lastName":"Tekle",
- "age":28,
- "email":"lidiya@lidiya.com"
- }
-]
-}`
-
-const usersObj = JSON.parse(usersText, undefined, 4)
-console.log(usersObj)
-```
-
-### Using a reviver function with JSON.parse()
-To use the reviver function as a formatter, we put the keys we want to format first name and last name value. Let us say, we are interested to format the firstName and lastName of the JSON data .
-
-```
-const usersText = `{
-"users":[
- {
- "firstName":"Asabeneh",
- "lastName":"Yetayeh",
- "age":250,
- "email":"asab@asb.com"
- },
- {
- "firstName":"Alex",
- "lastName":"James",
- "age":25,
- "email":"alex@alex.com"
- },
- {
- "firstName":"Lidiya",
- "lastName":"Tekle",
- "age":28,
- "email":"lidiya@lidiya.com"
- }
-]
-}`
-
-const usersObj = JSON.parse(usersText, (key, value) => {
- let newValue =
- typeof value == 'string' && key != 'email' ? value.toUpperCase() : value
- return newValue
-})
-console.log(usersObj)
-```
-
-The JSON.parse() is very handy to use. You do not have to pass optional parameter, you can just use it with the required parameter and you will achieve quite a lot.
-
-### Converting Object to JSON
-
-When we want to change the object to JSON we use JSON.stringify(). The stringify method takes one required parameter and two optional parameters. The replacer is used as filter and the space is an indentations. If we do not want to filter out any of the keys from the object we can just pass undefined.
-
-```
-JSON.stringify(obj, replacer, space)
-// json or text , the data
-// reviver is an optional callback function
-```
-
-Let us convert the following object to a string. First let use keep all the keys and also let us have 4 space indentation.
-
-```
-const users = {
- Alex: {
- email: 'alex@alex.com',
- skills: ['HTML', 'CSS', 'JavaScript'],
- age: 20,
- isLoggedIn: false,
- points: 30
- },
- Asab: {
- email: 'asab@asab.com',
- skills: [
- 'HTML',
- 'CSS',
- 'JavaScript',
- 'Redux',
- 'MongoDB',
- 'Express',
- 'React',
- 'Node'
- ],
- age: 25,
- isLoggedIn: false,
- points: 50
- },
- Brook: {
- email: 'daniel@daniel.com',
- skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],
- age: 30,
- isLoggedIn: true,
- points: 50
- },
- Daniel: {
- email: 'daniel@alex.com',
- skills: ['HTML', 'CSS', 'JavaScript', 'Python'],
- age: 20,
- isLoggedIn: false,
- points: 40
- },
- John: {
- email: 'john@john.com',
- skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],
- age: 20,
- isLoggedIn: true,
- points: 50
- },
- Thomas: {
- email: 'thomas@thomas.com',
- skills: ['HTML', 'CSS', 'JavaScript', 'React'],
- age: 20,
- isLoggedIn: false,
- points: 40
- },
- Paul: {
- email: 'paul@paul.com',
- skills: [
- 'HTML',
- 'CSS',
- 'JavaScript',
- 'MongoDB',
- 'Express',
- 'React',
- 'Node'
- ],
- age: 20,
- isLoggedIn: false,
- points: 40
- }
-}
-
-const txt = JSON.stringify(users, undefined, 4)
-console.log(txt) // text means JSON- because json is a string form of an object.
-```
-```
-{
- "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
- }
-}
-```
-
-### Using a Filter Array with JSON.stringify
-
-Now, lets use the replacer as a filter. The user object has long list of keys but we are interested only in few of them. We put the keys we want to keep in array as show in the example and use it the place of the replacer.
-
-```
-const user = {
- firstName: 'Asabeneh',
- lastName: 'Yetayeh',
- country: 'Finland',
- city: 'Helsinki',
- email: 'alex@alex.com',
- skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Python'],
- age: 250,
- isLoggedIn: false,
- points: 30
-}
-
-const txt = JSON.stringify(user,['firstName', 'lastName', 'country', 'city', 'age'],4)
-console.log(txt)
-```
-```
-{
- "firstName": "Asabeneh",
- "lastName": "Yetayeh",
- "country": "Finland",
- "city": "Helsinki",
- "age": 250
-}
-```
\ No newline at end of file
diff --git a/17_JSON/Ch17_pgm_01.js b/17_JS_JSON/cH17_PRO_01.JS
similarity index 73%
rename from 17_JSON/Ch17_pgm_01.js
rename to 17_JS_JSON/cH17_PRO_01.JS
index f775dbe..d72d136 100644
--- a/17_JSON/Ch17_pgm_01.js
+++ b/17_JS_JSON/cH17_PRO_01.JS
@@ -8,6 +8,19 @@ const student = {
isMarried:true,
skills:['HTML', 'CSS', 'JS', 'React','Node', 'Python', ]
}
+const skillsJSON = JSON.stringify(skills);
+console.log(skillsJSON);
+
+const ageJSON = JSON.stringify(age);
+console.log(ageJSON);
+
+const isMarriedJSON = JSON.stringify(isMarried);
+console.log(isMarriedJSON);
+
+const studentJSON = JSON.stringify(student);
+console.log(studentJSON);
+
+
const txt = `{
"Alex": {
"email": "alex@alex.com",
@@ -61,20 +74,6 @@ const txt = `{
"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": [
@@ -102,20 +101,21 @@ const txt = `{
"isLoggedIn": false,
"points": 40
}
-}
-`
-
+}`
-// Level 1
+const users = JSON.parse(txt);
-// 1. Change skills array to JSON using JSON.stringify()
-// 2. Stringify the age variable
-// 3. Stringify the isMarried variable
-// 4. Stringify the student object
+let maxSkills = 0;
+let userWithMaxSkills = null;
-// Level 2
-// 1. Stringify the students object with only firstName, lastName and skills properties
+for (const user in users) {
+ if (users.hasOwnProperty(user)) {
+ const skillsCount = users[user].skills.length;
+ if (skillsCount > maxSkills) {
+ maxSkills = skillsCount;
+ userWithMaxSkills = user;
+ }
+ }
+}
-// Level 3
-// 1. Parse the txt JSON to object.
-// 2. Find the user who has many skills from the variable stored in txt.
\ No newline at end of file
+console.log(`User with the most skills is: ${userWithMaxSkills}`);
\ No newline at end of file
diff --git a/18_JS_WEB_STORAGE/Ch18_pro_01.js b/18_JS_WEB_STORAGE/Ch18_pro_01.js
new file mode 100644
index 0000000..4c0c60a
--- /dev/null
+++ b/18_JS_WEB_STORAGE/Ch18_pro_01.js
@@ -0,0 +1,73 @@
+// Sample data
+const firstName = 'Anne';
+const age = 20;
+const country = 'India';
+const city = 'Chennai';
+
+
+localStorage.setItem('Name', firstName);
+localStorage.setItem('age', age);
+localStorage.setItem('country', country);
+localStorage.setItem('city', city);
+
+
+const student = {
+ firstName: 'Jane',
+ lastName: 'Smith',
+ age: 25,
+ skills: ['HTML', 'CSS', 'JavaScript'],
+ country: 'Canada',
+ enrolled: true
+};
+
+localStorage.setItem('student', JSON.stringify(student));
+
+
+function createPersonAccount(firstName) {
+ let incomes = [];
+ let expenses = [];
+
+ function addIncome(description, amount) {
+ incomes.push({ description, amount });
+ localStorage.setItem('incomes', JSON.stringify(incomes)); // Store incomes in localStorage
+ }
+
+
+ function addExpense(description, amount) {
+ expenses.push({ description, amount });
+ localStorage.setItem('expenses', JSON.stringify(expenses)); // Store expenses in localStorage
+ }
+
+
+ function totalIncome() {
+ return incomes.reduce((total, item) => total + item.amount, 0);
+ }
+
+
+ function totalExpense() {
+ return expenses.reduce((total, item) => total + item.amount, 0);
+ }
+
+ function accountInfo() {
+ return `${firstName} ${lastName}'s account:\nTotal Income: ${totalIncome()}\nTotal Expense: ${totalExpense()}`;
+ }
+
+
+ function accountBalance() {
+ return totalIncome() - totalExpense();
+ }
+
+ return { firstName, incomes, expenses, addIncome, addExpense, totalIncome, totalExpense, accountInfo, accountBalance };
+}
+
+
+const maxAccount = createPersonAccount('Max');
+
+
+maxAccount.addIncome('Salary', 3000);
+maxAccount.addIncome('Petrol', 1000);
+maxAccount.addExpense('Rent', 1200);
+maxAccount.addExpense('Food', 300);
+
+
+localStorage.setItem('maxAccount', JSON.stringify(maxAccount));
\ No newline at end of file
diff --git a/18_JS_Web_storage/Ch18_pgm_01.js b/18_JS_Web_storage/Ch18_pgm_01.js
deleted file mode 100644
index 1a6e556..0000000
--- a/18_JS_Web_storage/Ch18_pgm_01.js
+++ /dev/null
@@ -1,18 +0,0 @@
-// Level 1
-
-// Store you first name, last name, age, country, city in your browser localStorage.
-
-
-// Level 2
-
-// 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.
-
-
-// Level 3
-
-// 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.
\ No newline at end of file
diff --git a/18_JS_Web_storage/web_storage.md b/18_JS_Web_storage/web_storage.md
deleted file mode 100644
index f0ffdff..0000000
--- a/18_JS_Web_storage/web_storage.md
+++ /dev/null
@@ -1,164 +0,0 @@
-# HTML5 Web Storage
-
-Web Storage(sessionStorage and localStorage) is a new HTML5 API offering important benefits over traditional cookies. Before HTML5, application data had to be stored in cookies, included in every server request. Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance. The data storage limit of cookies in many web browsers is about 4 KB per cookie. We Storages can store far larger data (at least 5MB) and never transferred to the server. All sites from the same or one origin can store and access the same data.
-
-The data being stored can be accessed using JavaScript, which gives you the ability to leverage client-side scripting to do many things that have traditionally involved server-side programming and relational databases. There are two Web Storage objects:
-
-- sessionStorage
-- localStorage
-
-localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed.
-
-It should be noted that data stored in either localStorage or sessionStorage is specific to the protocol of the page.
-
-The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings).
-
-
-
-### sessionStorage
-
-sessionStorage is only available within the browser tab or window session. It’s designed to store data in a single web page session. That means if the window is closed the session data will be removed. Since sessionStorage and localStorage has similar methods, we will focus only on localStorage.
-
-### localStorage
-
-The HTML5 localStorage is the para of the web storage API which is used to store data on the browser with no expiration data. The data will be available on the browser even after the browser is closed. localStorage is kept even between browser sessions. This means data is still available when the browser is closed and reopened, and also instantly between tabs and windows.
-
-Web Storage data is, in both cases, not available between different browsers. For example, storage objects created in Firefox cannot be accessed in Internet Explorer, exactly like cookies. There are five methods to work on local storage: setItem(), getItem(), removeItem(), clear(), key()
-
-#### Use case of Web Storages
-
-Some use case of Web Storages are
-
-- store data temporarily
-- saving products that the user places in his shopping cart
-- data can be made available between page requests, multiple browser tabs, and also between browser sessions using localStorage
-- can be used offline completely using localStorage
-- Web Storage can be a great performance win when some static data is stored on the client to minimize the number of subsequent requests. Even images can be stored in strings using Base64 encoding.
-- can be used for user authentication method
-
-For the examples mentioned above, it makes sense to use localStorage. You may be wondering, then, when we should use sessionStorage.
-
-In cases, we want to to get rid of the data as soon as the window is closed. Or, perhaps, if we do not want the application to interfere with the same application that’s open in another window. These scenarios are served best with sessionStorage.
-
-Now, let us see how make use of these Web Storage APIs.
-
-### HTML5 Web Storage Objects
-
-HTML web storage provides two objects for storing data on the client:
-
-- window.localStorage - stores data with no expiration date
-- window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)Most modern browsers support Web Storage, however it is good to check browser support for localStorage and sessionStorage. Let us see the available methods for the Web Storage objects.
-
-**Web Storage objects:**
-
-* localStorage - to display the localStorage object
-* localStorage.clear() - to remove everything in the local storage
-* localStorage.setItem() - to store data in the localStorage. It takes a key and a value parameters.
-* localStorage.getItem() - to display data stored in the localStorage. It takes a key as a parameter.
-* localStorage.removeItem() - to remove stored item form a localStorage. It takes key as a parameter.
-* localStorage.key() - to display a data stored in a localStorage. It takes index as a parameter.
-
-
-
-### Setting item to the localStorage
-
-When we set data to be stored in a localStorage, it will be stored as a string. If we are storing an array or an object, we should stringify it first to keep the format unless otherwise we lose the array structure or the object structure of the original data.
-
-We store data in the localStorage using the localStorage.setItem method.
-
-```
-//syntax
-localStorage.setItem('key', 'value')
-```
-
-- Storing string in a localStorage
-```
-localStorage.setItem('firstName', 'Asabeneh') // since the value is string we do not stringify it
-console.log(localStorage)
-```
-```
-Storage {firstName: 'Asabeneh', length: 1}
-```
-
-- Storing number in a local storage
-```
-localStorage.setItem('age', 200)
-console.log(localStorage)
-```
-```
- Storage {age: '200', firstName: 'Asabeneh', length: 2}
- ```
-- Storing an array in a localStorage. If we are storing an array, an object or object array, we should stringify the object first. See the example below.
-```
-const skills = ['HTML', 'CSS', 'JS', 'React']
-//Skills array has to be stringified first to keep the format.
-const skillsJSON = JSON.stringify(skills, undefined, 4)
-localStorage.setItem('skills', skillsJSON)
-console.log(localStorage)
-```
-```
-Storage {age: '200', firstName: 'Asabeneh', skills: 'HTML,CSS,JS,React', length: 3}
-```
-```
-let skills = [
- { tech: 'HTML', level: 10 },
- { tech: 'CSS', level: 9 },
- { tech: 'JS', level: 8 },
- { tech: 'React', level: 9 },
- { tech: 'Redux', level: 10 },
- { tech: 'Node', level: 8 },
- { tech: 'MongoDB', level: 8 }
-]
-
-let skillJSON = JSON.stringify(skills)
-localStorage.setItem('skills', skillJSON)
-```
-- Storing an object in a localStorage. Before we storage objects to a localStorage, the object has to be stringified.
-```
-const user = {
- firstName: 'Asabeneh',
- age: 250,
- skills: ['HTML', 'CSS', 'JS', 'React']
-}
-
-const userText = JSON.stringify(user, undefined, 4)
-localStorage.setItem('user', userText)
-```
-
-### Getting item from localStorage
-
-We get data from the local storage using localStorage.getItem() method.
-
-```
-//syntax
-localStorage.getItem('key')
-```
-
-```
-let firstName = localStorage.getItem('firstName')
-let age = localStorage.getItem('age')
-let skills = localStorage.getItem('skills')
-console.log(firstName, age, skills)
-```
-```
- 'Asabeneh', '200', '['HTML','CSS','JS','React']'
- ```
-
-As you can see the skill is in a string format. Let us use JSON.parse() to parse it to normal array.
-
-```
-let skills = localStorage.getItem('skills')
-let skillsObj = JSON.parse(skills, undefined, 4)
-console.log(skillsObj)
-```
-```
-['HTML','CSS','JS','React']
-```
-
-### Clearing the localStorage
-
-The clear method, will clear everything stored in the local storage
-
-```
-localStorage.clear()
-```
\ No newline at end of file
diff --git a/19_JS_CLASSES/Ch19_pro_01.js b/19_JS_CLASSES/Ch19_pro_01.js
new file mode 100644
index 0000000..747b4f1
--- /dev/null
+++ b/19_JS_CLASSES/Ch19_pro_01.js
@@ -0,0 +1,134 @@
+
+class Animal {
+ constructor(name, age, color, legs) {
+ this.name = name;
+ this.age = age;
+ this.color = color;
+ this.legs = legs;
+ }
+
+ displayInfo() {
+ console.log(`Name: ${this.name}, Age: ${this.age}, Color: ${this.color}, Legs: ${this.legs}`);
+ }
+}
+
+
+class Dog extends Animal {
+ constructor(name, age, color) {
+ super(name, age, color, 4);
+ }
+
+ displayInfo() {
+ console.log(`Dog - Name: ${this.name}, Age: ${this.age}, Color: ${this.color}, Legs: ${this.legs}`);
+ }
+}
+
+
+class Cat extends Animal {
+ constructor(name, age, color) {
+ super(name, age, color, 4);
+ }
+
+ displayInfo() {
+ console.log(`Cat - Name: ${this.name}, Age: ${this.age}, Color: ${this.color}, Legs: ${this.legs}`);
+ }
+}
+
+class Statistics {
+ constructor(data) {
+ this.data = data;
+ }
+
+ count() {
+ return this.data.length;
+ }
+
+ sum() {
+ return this.data.reduce((acc, curr) => acc + curr, 0);
+ }
+
+ min() {
+ return Math.min(...this.data);
+ }
+
+ max() {
+ return Math.max(...this.data);
+ }
+
+ range() {
+ return this.max() - this.min();
+ }
+
+ mean() {
+ return this.sum() / this.count();
+ }
+
+ median() {
+ const sorted = [...this.data].sort((a, b) => a - b);
+ const middle = Math.floor(sorted.length / 2);
+ if (sorted.length % 2 === 0) {
+ return (sorted[middle - 1] + sorted[middle]) / 2;
+ } else {
+ return sorted[middle];
+ }
+ }
+
+ mode() {
+ const freqMap = {};
+ this.data.forEach(num => {
+ freqMap[num] = freqMap[num] ? freqMap[num] + 1 : 1;
+ });
+
+ let mode = [];
+ let maxFreq = 0;
+ for (const num in freqMap) {
+ if (freqMap[num] > maxFreq) {
+ mode = [parseInt(num)];
+ maxFreq = freqMap[num];
+ } else if (freqMap[num] === maxFreq) {
+ mode.push(parseInt(num));
+ }
+ }
+
+ return { mode: mode, count: maxFreq };
+ }
+
+ var() {
+ const mean = this.mean();
+ const sqDiffs = this.data.map(num => (num - mean) ** 2);
+ return sqDiffs.reduce((acc, curr) => acc + curr, 0) / this.count();
+ }
+
+ std() {
+ return Math.sqrt(this.var());
+ }
+
+ freqDist() {
+ const freqMap = {};
+ this.data.forEach(num => {
+ freqMap[num] = freqMap[num] ? freqMap[num] + 1 : 1;
+ });
+
+ const freqArray = Object.entries(freqMap)
+ .map(([num, freq]) => [freq, parseInt(num)])
+ .sort(([freq1], [freq2]) => freq2 - freq1); // Sort by frequency in descending order
+
+ return freqArray;
+ }
+}
+
+
+const ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26];
+const statistics = new Statistics(ages);
+
+console.log('Count:', statistics.count()); // 25
+console.log('Sum: ', statistics.sum()); // 744
+console.log('Min: ', statistics.min()); // 24
+console.log('Max: ', statistics.max()); // 38
+console.log('Range: ', statistics.range()); // 14
+console.log('Mean: ', statistics.mean()); // 29.76
+console.log('Median: ', statistics.median()); // 29
+console.log('Mode: ', statistics.mode()); // { mode: [26], count: 5 }
+console.log('Variance: ', statistics.var()); // 17.1752
+console.log('Standard Deviation: ', statistics.std()); // 4.143
+console.log('Frequency Distribution: ', statistics.freqDist());
\ No newline at end of file
diff --git a/19_JS_Classes/Ch19_pgm_01.js b/19_JS_Classes/Ch19_pgm_01.js
deleted file mode 100644
index 825210a..0000000
--- a/19_JS_Classes/Ch19_pgm_01.js
+++ /dev/null
@@ -1,34 +0,0 @@
-// Level 1
-
-// 1. Create an Animal class. The class will have name, age, color, legs properties and create
-// different methods
-// 2. Create a Dog and Cat child class from the Animal Class.
-
-// Level 2
-
-// Override the method you create in Animal class
-
-// Level 3
-
-// 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.
-
-ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26]
-
-console.log('Count:', statistics.count()) // 25
-console.log('Sum: ', statistics.sum()) // 744
-console.log('Min: ', statistics.min()) // 24
-console.log('Max: ', statistics.max()) // 38
-console.log('Range: ', statistics.range()) // 14
-console.log('Mean: ', statistics.mean()) // 30
-console.log('Median: ',statistics.median()) // 29
-console.log('Mode: ', statistics.mode()) // {'mode': 26, 'count': 5}
-console.log('Variance: ',statistics.var()) // 17.5
-console.log('Standard Deviation: ', statistics.std()) // 4.2
-console.log('Variance: ',statistics.var()) // 17.5
-console.log('Frequency Distribution: ',statistics.freqDist()) // [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
-
diff --git a/19_JS_Classes/classes.md b/19_JS_Classes/classes.md
deleted file mode 100644
index 38aaa11..0000000
--- a/19_JS_Classes/classes.md
+++ /dev/null
@@ -1,594 +0,0 @@
-# Classes
-
-JavaScript is an object oriented programming language. Everything in JavScript is an object, with its properties and methods. We create class to create an object. A Class is like an object constructor, or a "blueprint" for creating objects. We instantiate a class to create an object. The class defines attributes and the behavior of the object, while the object, on the other hand, represents the class.
-
-Once we create a class we can create object from it whenever we want. Creating an object from a class is called class instantiation.
-
-In the object section, we saw how to create an object literal. Object literal is a singleton. If we want to get a similar object , we have to write it. However, class allows to create many objects. This helps to reduce amount of code and repetition of code.
-
-### Defining a classes
-
-To define a class in JavaScript we need the keyword class , the name of a class in CamelCase and block code(two curly brackets). Let us create a class name Person.
-
-```
-// syntax
-class ClassName {
- // code goes here
-}
-```
-
-**Example:**
-```
-class Person {
- // code goes here
-}
-```
-
-We have created an Person class but it does not have any thing inside.
-
-### Class Instantiation
-
-Instantiation class means creating an object from a class. We need the keyword new and we call the name of the class after the word new.
-
-Let us create a dog object from our Person class.
-
-```
-class Person {
- // code goes here
-}
-const person = new Person()
-console.log(person)
-```
-```
-Person {}
-```
-
-As you can see, we have created a person object. Since the class did not have any properties yet the object is also empty.
-
-Let use the class constructor to pass different properties for the class.
-
-## Class Constructor
-
-The constructor is a builtin function which allows as to create a blueprint for our object. The constructor function starts with a keyword constructor followed by a parenthesis. Inside the parenthesis we pass the properties of the object as parameter. We use the this keyword to attach the constructor parameters with the class.
-
-The following Person class constructor has firstName and lastName property. These properties are attached to the Person class using this keyword. This refers to the class itself.
-
-```
-class Person {
- constructor(firstName, lastName) {
- console.log(this) // Check the output from here
- this.firstName = firstName
- this.lastName = lastName
- }
-}
-
-const person = new Person()
-
-console.log(person)
-```
-```
-Person {firstName: undefined, lastName:undefined}
-```
-
-All the keys of the object are undefined. When ever we instantiate we should pass the value of the properties. Let us pass value at this time when we instantiate the class.
-```
-class Person {
- constructor(firstName, lastName) {
- this.firstName = firstName
- this.lastName = lastName
- }
-}
-
-const person1 = new Person('Asabeneh', 'Yetayeh')
-
-console.log(person1)
-```
-```
-Person {firstName: "Asabeneh", lastName: "Yetayeh"}
-```
-
-As we have stated at the very beginning that once we create a class we can create many object using the class. Now, let us create many person objects using the Person class.
-```
-class Person {
- constructor(firstName, lastName) {
- console.log(this) // Check the output from here
- this.firstName = firstName
- this.lastName = lastName
- }
-}
-
-const person1 = new Person('Asabeneh', 'Yetayeh')
-const person2 = new Person('Lidiya', 'Tekle')
-const person3 = new Person('Abraham', 'Yetayeh')
-
-console.log(person1)
-console.log(person2)
-console.log(person3)
-```
-```
-Person {firstName: "Asabeneh", lastName: "Yetayeh"}
-Person {firstName: "Lidiya", lastName: "Tekle"}
-Person {firstName: "Abraham", lastName: "Yetayeh"}
-```
-
-Using the class Person we created three persons object. As you can see our class did not many properties let us add more properties to the class.
-
-```
-class Person {
- constructor(firstName, lastName, age, country, city) {
- console.log(this) // Check the output from here
- this.firstName = firstName
- this.lastName = lastName
- this.age = age
- this.country = country
- this.city = city
- }
-}
-
-const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
-
-console.log(person1)
-```
-```
-Person {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki"}
-```
-
-### Default values with constructor
-
-The constructor function properties may have a default value like other regular functions.
-
-```
-class Person {
- constructor(
- firstName = 'Asabeneh',
- lastName = 'Yetayeh',
- age = 250,
- country = 'Finland',
- city = 'Helsinki'
- ) {
- this.firstName = firstName
- this.lastName = lastName
- this.age = age
- this.country = country
- this.city = city
- }
-}
-
-const person1 = new Person() // it will take the default values
-const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
-
-console.log(person1)
-console.log(person2)
-```
-```
-Person {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki"}
-Person {firstName: "Lidiya", lastName: "Tekle", age: 28, country: "Finland", city: "Espoo"}
-```
-
-## Class methods
-
-The constructor inside a class is a builtin function which allow us to create a blueprint for the object. In a class we can create class methods. Methods are JavaScript functions inside the class. Let us create some class methods.
-```
-class Person {
- constructor(firstName, lastName, age, country, city) {
- this.firstName = firstName
- this.lastName = lastName
- this.age = age
- this.country = country
- this.city = city
- }
- getFullName() {
- const fullName = this.firstName + ' ' + this.lastName
- return fullName
- }
-}
-
-const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
-const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
-
-console.log(person1.getFullName())
-console.log(person2.getFullName())
-```
-```
-Asabeneh Yetayeh
-test.js:19 Lidiya Tekle
-```
-
-### Properties with initial value
-
-When we create a class for some properties we may have an initial value. For instance if you are playing a game, you starting score will be zero. So, we may have a starting score or score which is zero. In other way, we may have an initial skill and we will acquire some skill after some time.
-
-```
-class Person {
- constructor(firstName, lastName, age, country, city) {
- this.firstName = firstName
- this.lastName = lastName
- this.age = age
- this.country = country
- this.city = city
- this.score = 0
- this.skills = []
- }
- getFullName() {
- const fullName = this.firstName + ' ' + this.lastName
- return fullName
- }
-}
-
-const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
-const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
-
-console.log(person1.score)
-console.log(person2.score)
-
-console.log(person1.skills)
-console.log(person2.skills)
-```
-```
-0
-0
-[]
-[]
-```
-
-A method could be regular method or a getter or a setter. Let us see, getter and setter.
-
-### getter
-
-The get method allow us to access value from the object. We write a get method using keyword get followed by a function. Instead of accessing properties directly from the object we use getter to get the value. See the example bellow
-
-```
-class Person {
- constructor(firstName, lastName, age, country, city) {
- this.firstName = firstName
- this.lastName = lastName
- this.age = age
- this.country = country
- this.city = city
- this.score = 0
- this.skills = []
- }
- getFullName() {
- const fullName = this.firstName + ' ' + this.lastName
- return fullName
- }
- get getScore() {
- return this.score
- }
- get getSkills() {
- return this.skills
- }
-}
-
-const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
-const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
-
-console.log(person1.getScore) // We do not need parenthesis to call a getter method
-console.log(person2.getScore)
-
-console.log(person1.getSkills)
-console.log(person2.getSkills)
-```
-```
-0
-0
-[]
-[]
-```
-
-### setter
-
-The setter method allow us to modify the value of certain properties. We write a setter method using keyword set followed by a function. See the example bellow.
-```
-class Person {
- constructor(firstName, lastName, age, country, city) {
- this.firstName = firstName
- this.lastName = lastName
- this.age = age
- this.country = country
- this.city = city
- this.score = 0
- this.skills = []
- }
- getFullName() {
- const fullName = this.firstName + ' ' + this.lastName
- return fullName
- }
- get getScore() {
- return this.score
- }
- get getSkills() {
- return this.skills
- }
- set setScore(score) {
- this.score += score
- }
- set setSkill(skill) {
- this.skills.push(skill)
- }
-}
-
-const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
-const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
-
-person1.setScore = 1
-person1.setSkill = 'HTML'
-person1.setSkill = 'CSS'
-person1.setSkill = 'JavaScript'
-
-person2.setScore = 1
-person2.setSkill = 'Planning'
-person2.setSkill = 'Managing'
-person2.setSkill = 'Organizing'
-
-console.log(person1.score)
-console.log(person2.score)
-
-console.log(person1.skills)
-console.log(person2.skills)
-```
-```
-1
-1
-["HTML", "CSS", "JavaScript"]
-["Planning", "Managing", "Organizing"]
-```
-
-Do not be puzzled by the difference between regular method and a getter. If you know how to make a regular method you are good. Let us add regular method called getPersonInfo in the Person class.
-```
-class Person {
- constructor(firstName, lastName, age, country, city) {
- this.firstName = firstName
- this.lastName = lastName
- this.age = age
- this.country = country
- this.city = city
- this.score = 0
- this.skills = []
- }
- getFullName() {
- const fullName = this.firstName + ' ' + this.lastName
- return fullName
- }
- get getScore() {
- return this.score
- }
- get getSkills() {
- return this.skills
- }
- set setScore(score) {
- this.score += score
- }
- set setSkill(skill) {
- this.skills.push(skill)
- }
- getPersonInfo() {
- let fullName = this.getFullName()
- let skills =
- this.skills.length > 0 &&
- this.skills.slice(0, this.skills.length - 1).join(', ') +
- ` and ${this.skills[this.skills.length - 1]}`
- let formattedSkills = skills ? `He knows ${skills}` : ''
-
- let info = `${fullName} is ${this.age}. He lives ${this.city}, ${this.country}. ${formattedSkills}`
- return info
- }
-}
-
-const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
-const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
-const person3 = new Person('John', 'Doe', 50, 'Mars', 'Mars city')
-
-person1.setScore = 1
-person1.setSkill = 'HTML'
-person1.setSkill = 'CSS'
-person1.setSkill = 'JavaScript'
-
-person2.setScore = 1
-person2.setSkill = 'Planning'
-person2.setSkill = 'Managing'
-person2.setSkill = 'Organizing'
-
-console.log(person1.getScore)
-console.log(person2.getScore)
-
-console.log(person1.getSkills)
-console.log(person2.getSkills)
-console.log(person3.getSkills)
-
-console.log(person1.getPersonInfo())
-console.log(person2.getPersonInfo())
-console.log(person3.getPersonInfo())
-```
-```
-1
-1
-["HTML", "CSS", "JavaScript"]
-["Planning", "Managing", "Organizing"]
-[]
-Asabeneh Yetayeh is 250. He lives Helsinki, Finland. He knows HTML, CSS and JavaScript
-Lidiya Tekle is 28. He lives Espoo, Finland. He knows Planning, Managing and Organizing
-John Doe is 50. He lives Mars city, Mars.
-```
-
-### Static method
-
-The static keyword defines a static method for a class. Static methods are not called on instances of the class. Instead, they are called on the class itself. These are often utility functions, such as functions to create or clone objects. An example of static method is Date.now(). The now method is called directly from the class.
-```
-class Person {
- constructor(firstName, lastName, age, country, city) {
- this.firstName = firstName
- this.lastName = lastName
- this.age = age
- this.country = country
- this.city = city
- this.score = 0
- this.skills = []
- }
- getFullName() {
- const fullName = this.firstName + ' ' + this.lastName
- return fullName
- }
- get getScore() {
- return this.score
- }
- get getSkills() {
- return this.skills
- }
- set setScore(score) {
- this.score += score
- }
- set setSkill(skill) {
- this.skills.push(skill)
- }
- getPersonInfo() {
- let fullName = this.getFullName()
- let skills =
- this.skills.length > 0 &&
- this.skills.slice(0, this.skills.length - 1).join(', ') +
- ` and ${this.skills[this.skills.length - 1]}`
-
- let formattedSkills = skills ? `He knows ${skills}` : ''
-
- let info = `${fullName} is ${this.age}. He lives ${this.city}, ${this.country}. ${formattedSkills}`
- return info
- }
- static favoriteSkill() {
- const skills = ['HTML', 'CSS', 'JS', 'React', 'Python', 'Node']
- const index = Math.floor(Math.random() * skills.length)
- return skills[index]
- }
- static showDateTime() {
- let now = new Date()
- let year = now.getFullYear()
- let month = now.getMonth() + 1
- let date = now.getDate()
- let hours = now.getHours()
- let minutes = now.getMinutes()
- if (hours < 10) {
- hours = '0' + hours
- }
- if (minutes < 10) {
- minutes = '0' + minutes
- }
-
- let dateMonthYear = date + '.' + month + '.' + year
- let time = hours + ':' + minutes
- let fullTime = dateMonthYear + ' ' + time
- return fullTime
- }
-}
-
-console.log(Person.favoriteSkill())
-console.log(Person.showDateTime())
-```
-```
-Node
-15.1.2020 23:56
-```
-
-The static methods are methods which can be used as utility functions.
-
-## Inheritance
-
-Using inheritance we can access all the properties and the methods of the parent class. This reduces repetition of code. If you remember, we have a Person parent class and we will create children from it. Our children class could be student, teach etc.
-```
-// syntax
-class ChildClassName extends {
- // code goes here
-}
-```
-
-Let us create a Student child class from Person parent class.
-```
-class Student extends Person {
- saySomething() {
- console.log('I am a child of the person class')
- }
-}
-
-const s1 = new Student('Asabeneh', 'Yetayeh', 'Finland', 250, 'Helsinki')
-console.log(s1)
-console.log(s1.saySomething())
-console.log(s1.getFullName())
-console.log(s1.getPersonInfo())
-```
-```
-Student {firstName: "Asabeneh", lastName: "Yetayeh", age: "Finland", country: 250, city: "Helsinki", …}
-I am a child of the person class
-Asabeneh Yetayeh
-Student {firstName: "Asabeneh", lastName: "Yetayeh", age: "Finland", country: 250, city: "Helsinki", …}
-Asabeneh Yetayeh is Finland. He lives Helsinki, 250.
-```
-
-### Overriding methods
-
-As you can see, we manage to access all the methods in the Person Class and we used it in the Student child class. We can customize the parent methods, we can add additional properties to a child class. If we want to customize, the methods and if we want to add extra properties, we need to use the constructor function the child class too. Inside the constructor function we call the super() function to access all the properties from the parent class. The Person class didn't have gender but now let us give gender property for the child class, Student. If the same method name used in the child class, the parent method will be overridden.
-
-```
-class Student extends Person {
- constructor(firstName, lastName, age, country, city, gender) {
- super(firstName, lastName, age, country, city)
- this.gender = gender
- }
-
- saySomething() {
- console.log('I am a child of the person class')
- }
- getPersonInfo() {
- let fullName = this.getFullName()
- let skills =
- this.skills.length > 0 &&
- this.skills.slice(0, this.skills.length - 1).join(', ') +
- ` and ${this.skills[this.skills.length - 1]}`
-
- let formattedSkills = skills ? `He knows ${skills}` : ''
- let pronoun = this.gender == 'Male' ? 'He' : 'She'
-
- let info = `${fullName} is ${this.age}. ${pronoun} lives in ${this.city}, ${this.country}. ${formattedSkills}`
- return info
- }
-}
-
-const s1 = new Student(
- 'Asabeneh',
- 'Yetayeh',
- 250,
- 'Finland',
- 'Helsinki',
- 'Male'
-)
-const s2 = new Student('Lidiya', 'Tekle', 28, 'Finland', 'Helsinki', 'Female')
-s1.setScore = 1
-s1.setSkill = 'HTML'
-s1.setSkill = 'CSS'
-s1.setSkill = 'JavaScript'
-
-s2.setScore = 1
-s2.setSkill = 'Planning'
-s2.setSkill = 'Managing'
-s2.setSkill = 'Organizing'
-
-console.log(s1)
-
-console.log(s1.saySomething())
-console.log(s1.getFullName())
-console.log(s1.getPersonInfo())
-
-console.log(s2.saySomething())
-console.log(s2.getFullName())
-console.log(s2.getPersonInfo())
-```
-```
-Student {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki", …}
-Student {firstName: "Lidiya", lastName: "Tekle", age: 28, country: "Finland", city: "Helsinki", …}
-I am a child of the person class
-Asabeneh Yetayeh
-Student {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki", …}
-Asabeneh Yetayeh is 250. He lives in Helsinki, Finland. He knows HTML, CSS and JavaScript
-I am a child of the person class
-Lidiya Tekle
-Student {firstName: "Lidiya", lastName: "Tekle", age: 28, country: "Finland", city: "Helsinki", …}
-Lidiya Tekle is 28. She lives in Helsinki, Finland. He knows Planning, Managing and Organizing
-Now, the getPersonInfo method has been overridden and it identifies if the person is male or female.
-```
\ No newline at end of file
diff --git a/20_JS_HIGHER_ORDER_FUNCTIONS/Ch20_pro_01.js b/20_JS_HIGHER_ORDER_FUNCTIONS/Ch20_pro_01.js
new file mode 100644
index 0000000..82da6d6
--- /dev/null
+++ b/20_JS_HIGHER_ORDER_FUNCTIONS/Ch20_pro_01.js
@@ -0,0 +1,67 @@
+const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'IceLand']
+const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
+const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+const products = [
+ { product: 'banana', price: 3 },
+ { product: 'mango', price: 6 },
+ { product: 'potato', price: ' ' },
+ { product: 'avocado', price: 8 },
+ { product: 'coffee', price: 10 },
+ { product: 'tea', price: '' },
+]
+// Executes a provided function once for each array element. It does not return a new array and is used when you want to perform an action for each element without altering the original array.
+//Creates a new array with all elements that pass the test implemented by the provided function.
+// Applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
+
+countries.forEach(country => console.log(country));
+names.forEach(name => console.log(name));
+numbers.forEach(number => console.log(number));
+const countriesUpperCase = countries.map(country => country.toUpperCase());
+console.log(countriesUpperCase);
+const countriesLength = countries.map(country => country.length);
+console.log(countriesLength);
+const numbersSquared = numbers.map(number => number ** 2);
+console.log(numbersSquared);
+const namesUpperCase = names.map(name => name.toUpperCase());
+console.log(namesUpperCase);
+const productPrices = products.map(product => product.price);
+console.log(productPrices);
+const countriesWithLand = countries.filter(country => country.includes('land'));
+console.log(countriesWithLand);
+const countriesWithSixChars = countries.filter(country => country.length === 6);
+console.log(countriesWithSixChars);
+const countriesWithSixOrMoreLetters = countries.filter(country => country.length >= 6);
+console.log(countriesWithSixOrMoreLetters);
+const countriesStartingWithE = countries.filter(country => country.startsWith('E'));
+console.log(countriesStartingWithE);
+const validPrices = products.filter(product => typeof product.price === 'number' && !isNaN(product.price));
+console.log(validPrices);
+function getStringLists(arr) {
+ return arr.filter(item => typeof item === 'string');
+}
+
+console.log(getStringLists([1, 'hello', true, 'world'])); // Output: ['hello', 'world']
+const sum = numbers.reduce((acc, curr) => acc + curr, 0);
+console.log(sum);
+const countriesSentence = countries.reduce((acc, curr, index) => {
+ if (index === countries.length - 1) {
+ return acc + ' and ' + curr;
+ } else {
+ return acc + ', ' + curr;
+ }
+}, 'Estonia');
+console.log(`${countriesSentence} are north European countries`);
+
+const hasNamesGreaterThanSeven = names.some(name => name.length > 7);
+console.log(hasNamesGreaterThanSeven);
+const allCountriesContainLand = countries.every(country => country.includes('land'));
+console.log(allCountriesContainLand);
+const countryWithSixLetters = countries.find(country => country.length === 6);
+console.log(countryWithSixLetters);
+const indexCountryWithSixLetters = countries.findIndex(country => country.length === 6);
+console.log(indexCountryWithSixLetters);
+const indexNorway = countries.findIndex(country => country === 'Norway');
+console.log(indexNorway);
+
+const indexRussia = countries.findIndex(country => country === 'Russia');
+console.log(indexRussia);
\ No newline at end of file
diff --git a/20_JS_HIGHER_ORDER_FUNCTIONS/Ch20_pro_02.js b/20_JS_HIGHER_ORDER_FUNCTIONS/Ch20_pro_02.js
new file mode 100644
index 0000000..81e84fa
--- /dev/null
+++ b/20_JS_HIGHER_ORDER_FUNCTIONS/Ch20_pro_02.js
@@ -0,0 +1,79 @@
+const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'IceLand']
+const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
+const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+const products = [
+ { product: 'banana', price: 3 },
+ { product: 'mango', price: 6 },
+ { product: 'potato', price: ' ' },
+ { product: 'avocado', price: 8 },
+ { product: 'coffee', price: 10 },
+ { product: 'tea', price: '' },
+]
+
+const totalPrice = products
+ .filter(product => typeof product.price === 'number' && !isNaN(product.price))
+ .map(product => product.price)
+ .reduce((acc, curr) => acc + curr, 0);
+
+console.log('Total Price of Products:', totalPrice);
+
+const totalPriceReduce = products.reduce((acc, curr) => {
+ if (typeof curr.price === 'number' && !isNaN(curr.price)) {
+ return acc + curr.price;
+ } else {
+ return acc;
+ }
+ }, 0);
+
+ console.log('Total Price of Products (Reduce):', totalPriceReduce);
+
+ const categorizeCountries = () => {
+ const patterns = ['land', 'ia', 'island', 'stan'];
+ return countries.filter(country => patterns.some(pattern => country.toLowerCase().includes(pattern)));
+ };
+
+ console.log('Categorized Countries:', categorizeCountries());
+
+ const getInitialLettersFrequency = () => {
+ const letterFrequency = {};
+ countries.forEach(country => {
+ const initial = country.charAt(0).toUpperCase();
+ letterFrequency[initial] = letterFrequency[initial] ? letterFrequency[initial] + 1 : 1;
+ });
+
+ return Object.entries(letterFrequency).map(([letter, count]) => ({ letter, count }));
+ };
+
+ console.log('Initial Letters Frequency:', getInitialLettersFrequency());
+
+ const getFirstTenCountries = () => countries.slice(0, 10);
+
+console.log('First Ten Countries:', getFirstTenCountries());
+
+const getLastTenCountries = () => countries.slice(-10);
+
+console.log('Last Ten Countries:', getLastTenCountries());
+
+
+const getMostFrequentInitialLetter = () => {
+ const letterFrequency = {};
+ countries.forEach(country => {
+ const initial = country.charAt(0).toUpperCase();
+ letterFrequency[initial] = letterFrequency[initial] ? letterFrequency[initial] + 1 : 1;
+ });
+
+ let mostFrequentLetter = '';
+ let maxCount = 0;
+
+ Object.entries(letterFrequency).forEach(([letter, count]) => {
+ if (count > maxCount) {
+ mostFrequentLetter = letter;
+ maxCount = count;
+ }
+ });
+
+ return mostFrequentLetter;
+ };
+
+ console.log('Most Frequent Initial Letter:', getMostFrequentInitialLetter());
+
\ No newline at end of file
diff --git a/24_JS_Project_3/countries_data.js b/20_JS_HIGHER_ORDER_FUNCTIONS/Ch20_pro_03.js
similarity index 97%
rename from 24_JS_Project_3/countries_data.js
rename to 20_JS_HIGHER_ORDER_FUNCTIONS/Ch20_pro_03.js
index ebbe951..6db4c95 100644
--- a/24_JS_Project_3/countries_data.js
+++ b/20_JS_HIGHER_ORDER_FUNCTIONS/Ch20_pro_03.js
@@ -1,3 +1,37 @@
+
+
+ function mostSpokenLanguages(countries, numLanguages) {
+ let allLanguages = [];
+ countries.forEach(country => {
+ allLanguages = allLanguages.concat(country.languages);
+ });
+
+ let languageCount = {};
+ allLanguages.forEach(language => {
+ if (language in languageCount) {
+ languageCount[language]++;
+ } else {
+ languageCount[language] = 1;
+ }
+ });
+
+
+ let sortedLanguages = Object.keys(languageCount).map(language => {
+ return { language: language, count: languageCount[language] };
+ }).sort((a, b) => b.count - a.count);
+
+ return sortedLanguages.slice(0, numLanguages);
+}
+
+function mostPopulatedCountries(countries, numCountries) {
+
+ let sortedCountries = countries.sort((a, b) => b.population - a.population);
+
+ return sortedCountries.slice(0, numCountries).map(country => {
+ return { country: country.name, population: country.population };
+ });
+}
+
const countries = [
{
name: 'Afghanistan',
@@ -2010,4 +2044,12 @@ const countries = [
flag: 'https://restcountries.eu/data/zwe.svg',
currency: 'Botswana pula'
}
- ]
\ No newline at end of file
+ ]
+
+// Example usage
+console.log(mostSpokenLanguages(countries, 10));
+console.log(mostSpokenLanguages(countries, 3));
+
+console.log(mostPopulatedCountries(countries, 10));
+console.log(mostPopulatedCountries(countries, 3));
+
diff --git a/20_JS_Higher_order_functions/Ch20_pgm_01.js b/20_JS_Higher_order_functions/Ch20_pgm_01.js
deleted file mode 100644
index f241f24..0000000
--- a/20_JS_Higher_order_functions/Ch20_pgm_01.js
+++ /dev/null
@@ -1,41 +0,0 @@
-// Level 1
-
-const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'IceLand']
-const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
-const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
-const products = [
- { product: 'banana', price: 3 },
- { product: 'mango', price: 6 },
- { product: 'potato', price: ' ' },
- { product: 'avocado', price: 8 },
- { product: 'coffee', price: 10 },
- { product: 'tea', price: '' },
-]
-
-
-// 1. Explain the difference between forEach, map, filter, and reduce.
-// 2. Define a callback function before you use it in forEach, map, filter or reduce.
-// 3. Use forEach to console.log each country in the countries array.
-// 4. Use forEach to console.log each name in the names array.
-// 5. Use forEach to console.log each number in the numbers array.
-// 6. Use map to create a new array by changing each country to uppercase in the countries array.
-// 7. Use map to create an array of countries length from countries array.
-// 8. Use map to create a new array by changing each number to square in the numbers array
-// 9. Use map to change to each name to uppercase in the names array
-// 10. Use map to map the products array to its corresponding prices.
-// 11. Use filter to filter out countries containing land.
-// 12. Use filter to filter out countries having six character.
-// 13. Use filter to filter out countries containing six letters and more in the country array.
-// 14. Use filter to filter out country start with 'E';
-// 15. Use filter to filter out only prices with values.
-// 16. Declare a function called getStringLists which takes an array as a parameter and then returns an array only with string items.
-// 17. Use reduce to sum all the numbers in the numbers array.
-// 18. Use reduce to concatenate all the countries and to produce this sentence: Estonia, Finland, Sweden, Denmark, Norway, and IceLand are north European countries
-// 19. Explain the difference between some and every
-// 20. Use some to check if some names' length greater than seven in names array
-// 21. Use every to check if all the countries contain the word land
-// 22. Explain the difference between find and findIndex.
-// 23. Use find to find the first country containing only six letters in the countries array
-// 24. Use findIndex to find the position of the first country containing only six letters in the countries array
-// 25. Use findIndex to find the position of Norway if it doesn't exist in the array you will get -1.
-// 26. Use findIndex to find the position of Russia if it doesn't exist in the array you will get -1.
\ No newline at end of file
diff --git a/20_JS_Higher_order_functions/Ch20_pgm_02.js b/20_JS_Higher_order_functions/Ch20_pgm_02.js
deleted file mode 100644
index bdc64ba..0000000
--- a/20_JS_Higher_order_functions/Ch20_pgm_02.js
+++ /dev/null
@@ -1,21 +0,0 @@
-// Level 2
-
-const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'IceLand']
-const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
-const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
-const products = [
- { product: 'banana', price: 3 },
- { product: 'mango', price: 6 },
- { product: 'potato', price: ' ' },
- { product: 'avocado', price: 8 },
- { product: 'coffee', price: 10 },
- { product: 'tea', price: '' },
-]
-
-// 1. Find the total price of products by chaining two or more array iterators(eg. arr.map(callback).filter(callback).reduce(callback))
-// 2. Find the sum of price of products using only reduce reduce(callback))
-// 3. Declare a function called categorizeCountries which returns an array of countries which have some common pattern(you find the countries array in this repository as countries.js(eg 'land', 'ia', 'island','stan')).
-// 4. Create a function which return an array of objects, which is the letter and the number of times the letter use to start with a name of a country.
-// 5. Declare a getFirstTenCountries function and return an array of ten countries. Use different functional programming to work on the countries.js array
-// 6. Declare a getLastTenCountries function which which returns the last ten countries in the countries array.
-// 7. Find out which letter is used many times as initial for a country name from the countries array (eg. Finland, Fiji, France etc)
\ No newline at end of file
diff --git a/20_JS_Higher_order_functions/Ch20_pgm_03.js b/20_JS_Higher_order_functions/Ch20_pgm_03.js
deleted file mode 100644
index 57f6b6c..0000000
--- a/20_JS_Higher_order_functions/Ch20_pgm_03.js
+++ /dev/null
@@ -1,54 +0,0 @@
-// Use the countries information, in the data folder. Sort countries by name, by capital, by population
-
-// *** Find the 10 most spoken languages:
-
-// Your output should look like this
-console.log(mostSpokenLanguages(countries, 10))
-[
-{country: 'English',count:91},
-{country: 'French',count:45},
-{country: 'Arabic',count:25},
-{country: 'Spanish',count:24},
-{country:'Russian',count:9},
-{country:'Portuguese', count:9},
-{country:'Dutch',count:8},
-{country:'German',count:7},
-{country:'Chinese',count:5},
-{country:'Swahili',count:4}
-]
-
-// Your output should look like this
-console.log(mostSpokenLanguages(countries, 3))
-[
-{country: 'English',count: 91},
-{country: 'French',count: 45},
-{country: 'Arabic',count: 25}
-]
-
-
-// *** Use countries_data.js file create a function which create the ten most populated countries
-
-console.log(mostPopulatedCountries(countries, 10))
-
-[
-{country: 'China', population: 1377422166},
-{country: 'India', population: 1295210000},
-{country: 'United States of America', population: 323947000},
-{country: 'Indonesia', population: 258705000},
-{country: 'Brazil', population: 206135893},
-{country: 'Pakistan', population: 194125062},
-{country: 'Nigeria', population: 186988000},
-{country: 'Bangladesh', population: 161006790},
-{country: 'Russian Federation', population: 146599183},
-{country: 'Japan', population: 126960000}
-]
-
-console.log(mostPopulatedCountries(countries, 3))
-[
-{country: 'China', population: 1377422166},
-{country: 'India', population: 1295210000},
-{country: 'United States of America', population: 323947000}
-]
-
-
-
diff --git a/20_JS_Higher_order_functions/data/countries_data.js b/20_JS_Higher_order_functions/data/countries_data.js
deleted file mode 100644
index 2ce0dac..0000000
--- a/20_JS_Higher_order_functions/data/countries_data.js
+++ /dev/null
@@ -1,2013 +0,0 @@
-const countries = [
- {
- name: 'Afghanistan',
- capital: 'Kabul',
- languages: ['Pashto', 'Uzbek', 'Turkmen'],
- population: 27657145,
- flag: 'https://restcountries.eu/data/afg.svg',
- currency: 'Afghan afghani'
- },
- {
- name: 'Åland Islands',
- capital: 'Mariehamn',
- languages: ['Swedish'],
- population: 28875,
- flag: 'https://restcountries.eu/data/ala.svg',
- currency: 'Euro'
- },
- {
- name: 'Albania',
- capital: 'Tirana',
- languages: ['Albanian'],
- population: 2886026,
- flag: 'https://restcountries.eu/data/alb.svg',
- currency: 'Albanian lek'
- },
- {
- name: 'Algeria',
- capital: 'Algiers',
- languages: ['Arabic'],
- population: 40400000,
- flag: 'https://restcountries.eu/data/dza.svg',
- currency: 'Algerian dinar'
- },
- {
- name: 'American Samoa',
- capital: 'Pago Pago',
- languages: ['English', 'Samoan'],
- population: 57100,
- flag: 'https://restcountries.eu/data/asm.svg',
- currency: 'United State Dollar'
- },
- {
- name: 'Andorra',
- capital: 'Andorra la Vella',
- languages: ['Catalan'],
- population: 78014,
- flag: 'https://restcountries.eu/data/and.svg',
- currency: 'Euro'
- },
- {
- name: 'Angola',
- capital: 'Luanda',
- languages: ['Portuguese'],
- population: 25868000,
- flag: 'https://restcountries.eu/data/ago.svg',
- currency: 'Angolan kwanza'
- },
- {
- name: 'Anguilla',
- capital: 'The Valley',
- languages: ['English'],
- population: 13452,
- flag: 'https://restcountries.eu/data/aia.svg',
- currency: 'East Caribbean dollar'
- },
- {
- name: 'Antarctica',
- capital: '',
- languages: ['English', 'Russian'],
- population: 1000,
- flag: 'https://restcountries.eu/data/ata.svg',
- currency: 'Australian dollar'
- },
- {
- name: 'Antigua and Barbuda',
- capital: "Saint John's",
- languages: ['English'],
- population: 86295,
- flag: 'https://restcountries.eu/data/atg.svg',
- currency: 'East Caribbean dollar'
- },
- {
- name: 'Argentina',
- capital: 'Buenos Aires',
- languages: ['Spanish', 'Guaraní'],
- population: 43590400,
- flag: 'https://restcountries.eu/data/arg.svg',
- currency: 'Argentine peso'
- },
- {
- name: 'Armenia',
- capital: 'Yerevan',
- languages: ['Armenian', 'Russian'],
- population: 2994400,
- flag: 'https://restcountries.eu/data/arm.svg',
- currency: 'Armenian dram'
- },
- {
- name: 'Aruba',
- capital: 'Oranjestad',
- languages: ['Dutch', '(Eastern) Punjabi'],
- population: 107394,
- flag: 'https://restcountries.eu/data/abw.svg',
- currency: 'Aruban florin'
- },
- {
- name: 'Australia',
- capital: 'Canberra',
- languages: ['English'],
- population: 24117360,
- flag: 'https://restcountries.eu/data/aus.svg',
- currency: 'Australian dollar'
- },
- {
- name: 'Austria',
- capital: 'Vienna',
- languages: ['German'],
- population: 8725931,
- flag: 'https://restcountries.eu/data/aut.svg',
- currency: 'Euro'
- },
- {
- name: 'Azerbaijan',
- capital: 'Baku',
- languages: ['Azerbaijani'],
- population: 9730500,
- flag: 'https://restcountries.eu/data/aze.svg',
- currency: 'Azerbaijani manat'
- },
- {
- name: 'Bahamas',
- capital: 'Nassau',
- languages: ['English'],
- population: 378040,
- flag: 'https://restcountries.eu/data/bhs.svg',
- currency: 'Bahamian dollar'
- },
- {
- name: 'Bahrain',
- capital: 'Manama',
- languages: ['Arabic'],
- population: 1404900,
- flag: 'https://restcountries.eu/data/bhr.svg',
- currency: 'Bahraini dinar'
- },
- {
- name: 'Bangladesh',
- capital: 'Dhaka',
- languages: ['Bengali'],
- population: 161006790,
- flag: 'https://restcountries.eu/data/bgd.svg',
- currency: 'Bangladeshi taka'
- },
- {
- name: 'Barbados',
- capital: 'Bridgetown',
- languages: ['English'],
- population: 285000,
- flag: 'https://restcountries.eu/data/brb.svg',
- currency: 'Barbadian dollar'
- },
- {
- name: 'Belarus',
- capital: 'Minsk',
- languages: ['Belarusian', 'Russian'],
- population: 9498700,
- flag: 'https://restcountries.eu/data/blr.svg',
- currency: 'New Belarusian ruble'
- },
- {
- name: 'Belgium',
- capital: 'Brussels',
- languages: ['Dutch', 'French', 'German'],
- population: 11319511,
- flag: 'https://restcountries.eu/data/bel.svg',
- currency: 'Euro'
- },
- {
- name: 'Belize',
- capital: 'Belmopan',
- languages: ['English', 'Spanish'],
- population: 370300,
- flag: 'https://restcountries.eu/data/blz.svg',
- currency: 'Belize dollar'
- },
- {
- name: 'Benin',
- capital: 'Porto-Novo',
- languages: ['French'],
- population: 10653654,
- flag: 'https://restcountries.eu/data/ben.svg',
- currency: 'West African CFA franc'
- },
- {
- name: 'Bermuda',
- capital: 'Hamilton',
- languages: ['English'],
- population: 61954,
- flag: 'https://restcountries.eu/data/bmu.svg',
- currency: 'Bermudian dollar'
- },
- {
- name: 'Bhutan',
- capital: 'Thimphu',
- languages: ['Dzongkha'],
- population: 775620,
- flag: 'https://restcountries.eu/data/btn.svg',
- currency: 'Bhutanese ngultrum'
- },
- {
- name: 'Bolivia (Plurinational State of)',
- capital: 'Sucre',
- languages: ['Spanish', 'Aymara', 'Quechua'],
- population: 10985059,
- flag: 'https://restcountries.eu/data/bol.svg',
- currency: 'Bolivian boliviano'
- },
- {
- name: 'Bonaire, Sint Eustatius and Saba',
- capital: 'Kralendijk',
- languages: ['Dutch'],
- population: 17408,
- flag: 'https://restcountries.eu/data/bes.svg',
- currency: 'United States dollar'
- },
- {
- name: 'Bosnia and Herzegovina',
- capital: 'Sarajevo',
- languages: ['Bosnian', 'Croatian', 'Serbian'],
- population: 3531159,
- flag: 'https://restcountries.eu/data/bih.svg',
- currency: 'Bosnia and Herzegovina convertible mark'
- },
- {
- name: 'Botswana',
- capital: 'Gaborone',
- languages: ['English', 'Tswana'],
- population: 2141206,
- flag: 'https://restcountries.eu/data/bwa.svg',
- currency: 'Botswana pula'
- },
- {
- name: 'Bouvet Island',
- capital: '',
- languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'],
- population: 0,
- flag: 'https://restcountries.eu/data/bvt.svg',
- currency: 'Norwegian krone'
- },
- {
- name: 'Brazil',
- capital: 'Brasília',
- languages: ['Portuguese'],
- population: 206135893,
- flag: 'https://restcountries.eu/data/bra.svg',
- currency: 'Brazilian real'
- },
- {
- name: 'British Indian Ocean Territory',
- capital: 'Diego Garcia',
- languages: ['English'],
- population: 3000,
- flag: 'https://restcountries.eu/data/iot.svg',
- currency: 'United States dollar'
- },
- {
- name: 'United States Minor Outlying Islands',
- capital: '',
- languages: ['English'],
- population: 300,
- flag: 'https://restcountries.eu/data/umi.svg',
- currency: 'United States Dollar'
- },
- {
- name: 'Virgin Islands (British)',
- capital: 'Road Town',
- languages: ['English'],
- population: 28514,
- flag: 'https://restcountries.eu/data/vgb.svg',
- currency: '[D]'
- },
- {
- name: 'Virgin Islands (U.S.)',
- capital: 'Charlotte Amalie',
- languages: ['English'],
- population: 114743,
- flag: 'https://restcountries.eu/data/vir.svg',
- currency: 'United States dollar'
- },
- {
- name: 'Brunei Darussalam',
- capital: 'Bandar Seri Begawan',
- languages: ['Malay'],
- population: 411900,
- flag: 'https://restcountries.eu/data/brn.svg',
- currency: 'Brunei dollar'
- },
- {
- name: 'Bulgaria',
- capital: 'Sofia',
- languages: ['Bulgarian'],
- population: 7153784,
- flag: 'https://restcountries.eu/data/bgr.svg',
- currency: 'Bulgarian lev'
- },
- {
- name: 'Burkina Faso',
- capital: 'Ouagadougou',
- languages: ['French', 'Fula'],
- population: 19034397,
- flag: 'https://restcountries.eu/data/bfa.svg',
- currency: 'West African CFA franc'
- },
- {
- name: 'Burundi',
- capital: 'Bujumbura',
- languages: ['French', 'Kirundi'],
- population: 10114505,
- flag: 'https://restcountries.eu/data/bdi.svg',
- currency: 'Burundian franc'
- },
- {
- name: 'Cambodia',
- capital: 'Phnom Penh',
- languages: ['Khmer'],
- population: 15626444,
- flag: 'https://restcountries.eu/data/khm.svg',
- currency: 'Cambodian riel'
- },
- {
- name: 'Cameroon',
- capital: 'Yaoundé',
- languages: ['English', 'French'],
- population: 22709892,
- flag: 'https://restcountries.eu/data/cmr.svg',
- currency: 'Central African CFA franc'
- },
- {
- name: 'Canada',
- capital: 'Ottawa',
- languages: ['English', 'French'],
- population: 36155487,
- flag: 'https://restcountries.eu/data/can.svg',
- currency: 'Canadian dollar'
- },
- {
- name: 'Cabo Verde',
- capital: 'Praia',
- languages: ['Portuguese'],
- population: 531239,
- flag: 'https://restcountries.eu/data/cpv.svg',
- currency: 'Cape Verdean escudo'
- },
- {
- name: 'Cayman Islands',
- capital: 'George Town',
- languages: ['English'],
- population: 58238,
- flag: 'https://restcountries.eu/data/cym.svg',
- currency: 'Cayman Islands dollar'
- },
- {
- name: 'Central African Republic',
- capital: 'Bangui',
- languages: ['French', 'Sango'],
- population: 4998000,
- flag: 'https://restcountries.eu/data/caf.svg',
- currency: 'Central African CFA franc'
- },
- {
- name: 'Chad',
- capital: "N'Djamena",
- languages: ['French', 'Arabic'],
- population: 14497000,
- flag: 'https://restcountries.eu/data/tcd.svg',
- currency: 'Central African CFA franc'
- },
- {
- name: 'Chile',
- capital: 'Santiago',
- languages: ['Spanish'],
- population: 18191900,
- flag: 'https://restcountries.eu/data/chl.svg',
- currency: 'Chilean peso'
- },
- {
- name: 'China',
- capital: 'Beijing',
- languages: ['Chinese'],
- population: 1377422166,
- flag: 'https://restcountries.eu/data/chn.svg',
- currency: 'Chinese yuan'
- },
- {
- name: 'Christmas Island',
- capital: 'Flying Fish Cove',
- languages: ['English'],
- population: 2072,
- flag: 'https://restcountries.eu/data/cxr.svg',
- currency: 'Australian dollar'
- },
- {
- name: 'Cocos (Keeling) Islands',
- capital: 'West Island',
- languages: ['English'],
- population: 550,
- flag: 'https://restcountries.eu/data/cck.svg',
- currency: 'Australian dollar'
- },
- {
- name: 'Colombia',
- capital: 'Bogotá',
- languages: ['Spanish'],
- population: 48759958,
- flag: 'https://restcountries.eu/data/col.svg',
- currency: 'Colombian peso'
- },
- {
- name: 'Comoros',
- capital: 'Moroni',
- languages: ['Arabic', 'French'],
- population: 806153,
- flag: 'https://restcountries.eu/data/com.svg',
- currency: 'Comorian franc'
- },
- {
- name: 'Congo',
- capital: 'Brazzaville',
- languages: ['French', 'Lingala'],
- population: 4741000,
- flag: 'https://restcountries.eu/data/cog.svg',
- currency: 'Central African CFA franc'
- },
- {
- name: 'Congo (Democratic Republic of the)',
- capital: 'Kinshasa',
- languages: ['French', 'Lingala', 'Kongo', 'Swahili', 'Luba-Katanga'],
- population: 85026000,
- flag: 'https://restcountries.eu/data/cod.svg',
- currency: 'Congolese franc'
- },
- {
- name: 'Cook Islands',
- capital: 'Avarua',
- languages: ['English'],
- population: 18100,
- flag: 'https://restcountries.eu/data/cok.svg',
- currency: 'New Zealand dollar'
- },
- {
- name: 'Costa Rica',
- capital: 'San José',
- languages: ['Spanish'],
- population: 4890379,
- flag: 'https://restcountries.eu/data/cri.svg',
- currency: 'Costa Rican colón'
- },
- {
- name: 'Croatia',
- capital: 'Zagreb',
- languages: ['Croatian'],
- population: 4190669,
- flag: 'https://restcountries.eu/data/hrv.svg',
- currency: 'Croatian kuna'
- },
- {
- name: 'Cuba',
- capital: 'Havana',
- languages: ['Spanish'],
- population: 11239004,
- flag: 'https://restcountries.eu/data/cub.svg',
- currency: 'Cuban convertible peso'
- },
- {
- name: 'Curaçao',
- capital: 'Willemstad',
- languages: ['Dutch', '(Eastern) Punjabi', 'English'],
- population: 154843,
- flag: 'https://restcountries.eu/data/cuw.svg',
- currency: 'Netherlands Antillean guilder'
- },
- {
- name: 'Cyprus',
- capital: 'Nicosia',
- languages: ['Greek (modern)', 'Turkish', 'Armenian'],
- population: 847000,
- flag: 'https://restcountries.eu/data/cyp.svg',
- currency: 'Euro'
- },
- {
- name: 'Czech Republic',
- capital: 'Prague',
- languages: ['Czech', 'Slovak'],
- population: 10558524,
- flag: 'https://restcountries.eu/data/cze.svg',
- currency: 'Czech koruna'
- },
- {
- name: 'Denmark',
- capital: 'Copenhagen',
- languages: ['Danish'],
- population: 5717014,
- flag: 'https://restcountries.eu/data/dnk.svg',
- currency: 'Danish krone'
- },
- {
- name: 'Djibouti',
- capital: 'Djibouti',
- languages: ['French', 'Arabic'],
- population: 900000,
- flag: 'https://restcountries.eu/data/dji.svg',
- currency: 'Djiboutian franc'
- },
- {
- name: 'Dominica',
- capital: 'Roseau',
- languages: ['English'],
- population: 71293,
- flag: 'https://restcountries.eu/data/dma.svg',
- currency: 'East Caribbean dollar'
- },
- {
- name: 'Dominican Republic',
- capital: 'Santo Domingo',
- languages: ['Spanish'],
- population: 10075045,
- flag: 'https://restcountries.eu/data/dom.svg',
- currency: 'Dominican peso'
- },
- {
- name: 'Ecuador',
- capital: 'Quito',
- languages: ['Spanish'],
- population: 16545799,
- flag: 'https://restcountries.eu/data/ecu.svg',
- currency: 'United States dollar'
- },
- {
- name: 'Egypt',
- capital: 'Cairo',
- languages: ['Arabic'],
- population: 91290000,
- flag: 'https://restcountries.eu/data/egy.svg',
- currency: 'Egyptian pound'
- },
- {
- name: 'El Salvador',
- capital: 'San Salvador',
- languages: ['Spanish'],
- population: 6520675,
- flag: 'https://restcountries.eu/data/slv.svg',
- currency: 'United States dollar'
- },
- {
- name: 'Equatorial Guinea',
- capital: 'Malabo',
- languages: ['Spanish', 'French'],
- population: 1222442,
- flag: 'https://restcountries.eu/data/gnq.svg',
- currency: 'Central African CFA franc'
- },
- {
- name: 'Eritrea',
- capital: 'Asmara',
- languages: ['Tigrinya', 'Arabic', 'English'],
- population: 5352000,
- flag: 'https://restcountries.eu/data/eri.svg',
- currency: 'Eritrean nakfa'
- },
- {
- name: 'Estonia',
- capital: 'Tallinn',
- languages: ['Estonian'],
- population: 1315944,
- flag: 'https://restcountries.eu/data/est.svg',
- currency: 'Euro'
- },
- {
- name: 'Ethiopia',
- capital: 'Addis Ababa',
- languages: ['Amharic'],
- population: 92206005,
- flag: 'https://restcountries.eu/data/eth.svg',
- currency: 'Ethiopian birr'
- },
- {
- name: 'Falkland Islands (Malvinas)',
- capital: 'Stanley',
- languages: ['English'],
- population: 2563,
- flag: 'https://restcountries.eu/data/flk.svg',
- currency: 'Falkland Islands pound'
- },
- {
- name: 'Faroe Islands',
- capital: 'Tórshavn',
- languages: ['Faroese'],
- population: 49376,
- flag: 'https://restcountries.eu/data/fro.svg',
- currency: 'Danish krone'
- },
- {
- name: 'Fiji',
- capital: 'Suva',
- languages: ['English', 'Fijian', 'Hindi', 'Urdu'],
- population: 867000,
- flag: 'https://restcountries.eu/data/fji.svg',
- currency: 'Fijian dollar'
- },
- {
- name: 'Finland',
- capital: 'Helsinki',
- languages: ['Finnish', 'Swedish'],
- population: 5491817,
- flag: 'https://restcountries.eu/data/fin.svg',
- currency: 'Euro'
- },
- {
- name: 'France',
- capital: 'Paris',
- languages: ['French'],
- population: 66710000,
- flag: 'https://restcountries.eu/data/fra.svg',
- currency: 'Euro'
- },
- {
- name: 'French Guiana',
- capital: 'Cayenne',
- languages: ['French'],
- population: 254541,
- flag: 'https://restcountries.eu/data/guf.svg',
- currency: 'Euro'
- },
- {
- name: 'French Polynesia',
- capital: 'Papeetē',
- languages: ['French'],
- population: 271800,
- flag: 'https://restcountries.eu/data/pyf.svg',
- currency: 'CFP franc'
- },
- {
- name: 'French Southern Territories',
- capital: 'Port-aux-Français',
- languages: ['French'],
- population: 140,
- flag: 'https://restcountries.eu/data/atf.svg',
- currency: 'Euro'
- },
- {
- name: 'Gabon',
- capital: 'Libreville',
- languages: ['French'],
- population: 1802278,
- flag: 'https://restcountries.eu/data/gab.svg',
- currency: 'Central African CFA franc'
- },
- {
- name: 'Gambia',
- capital: 'Banjul',
- languages: ['English'],
- population: 1882450,
- flag: 'https://restcountries.eu/data/gmb.svg',
- currency: 'Gambian dalasi'
- },
- {
- name: 'Georgia',
- capital: 'Tbilisi',
- languages: ['Georgian'],
- population: 3720400,
- flag: 'https://restcountries.eu/data/geo.svg',
- currency: 'Georgian Lari'
- },
- {
- name: 'Germany',
- capital: 'Berlin',
- languages: ['German'],
- population: 81770900,
- flag: 'https://restcountries.eu/data/deu.svg',
- currency: 'Euro'
- },
- {
- name: 'Ghana',
- capital: 'Accra',
- languages: ['English'],
- population: 27670174,
- flag: 'https://restcountries.eu/data/gha.svg',
- currency: 'Ghanaian cedi'
- },
- {
- name: 'Gibraltar',
- capital: 'Gibraltar',
- languages: ['English'],
- population: 33140,
- flag: 'https://restcountries.eu/data/gib.svg',
- currency: 'Gibraltar pound'
- },
- {
- name: 'Greece',
- capital: 'Athens',
- languages: ['Greek (modern)'],
- population: 10858018,
- flag: 'https://restcountries.eu/data/grc.svg',
- currency: 'Euro'
- },
- {
- name: 'Greenland',
- capital: 'Nuuk',
- languages: ['Kalaallisut'],
- population: 55847,
- flag: 'https://restcountries.eu/data/grl.svg',
- currency: 'Danish krone'
- },
- {
- name: 'Grenada',
- capital: "St. George's",
- languages: ['English'],
- population: 103328,
- flag: 'https://restcountries.eu/data/grd.svg',
- currency: 'East Caribbean dollar'
- },
- {
- name: 'Guadeloupe',
- capital: 'Basse-Terre',
- languages: ['French'],
- population: 400132,
- flag: 'https://restcountries.eu/data/glp.svg',
- currency: 'Euro'
- },
- {
- name: 'Guam',
- capital: 'Hagåtña',
- languages: ['English', 'Chamorro', 'Spanish'],
- population: 184200,
- flag: 'https://restcountries.eu/data/gum.svg',
- currency: 'United States dollar'
- },
- {
- name: 'Guatemala',
- capital: 'Guatemala City',
- languages: ['Spanish'],
- population: 16176133,
- flag: 'https://restcountries.eu/data/gtm.svg',
- currency: 'Guatemalan quetzal'
- },
- {
- name: 'Guernsey',
- capital: 'St. Peter Port',
- languages: ['English', 'French'],
- population: 62999,
- flag: 'https://restcountries.eu/data/ggy.svg',
- currency: 'British pound'
- },
- {
- name: 'Guinea',
- capital: 'Conakry',
- languages: ['French', 'Fula'],
- population: 12947000,
- flag: 'https://restcountries.eu/data/gin.svg',
- currency: 'Guinean franc'
- },
- {
- name: 'Guinea-Bissau',
- capital: 'Bissau',
- languages: ['Portuguese'],
- population: 1547777,
- flag: 'https://restcountries.eu/data/gnb.svg',
- currency: 'West African CFA franc'
- },
- {
- name: 'Guyana',
- capital: 'Georgetown',
- languages: ['English'],
- population: 746900,
- flag: 'https://restcountries.eu/data/guy.svg',
- currency: 'Guyanese dollar'
- },
- {
- name: 'Haiti',
- capital: 'Port-au-Prince',
- languages: ['French', 'Haitian'],
- population: 11078033,
- flag: 'https://restcountries.eu/data/hti.svg',
- currency: 'Haitian gourde'
- },
- {
- name: 'Heard Island and McDonald Islands',
- capital: '',
- languages: ['English'],
- population: 0,
- flag: 'https://restcountries.eu/data/hmd.svg',
- currency: 'Australian dollar'
- },
- {
- name: 'Holy See',
- capital: 'Rome',
- languages: ['Latin', 'Italian', 'French', 'German'],
- population: 451,
- flag: 'https://restcountries.eu/data/vat.svg',
- currency: 'Euro'
- },
- {
- name: 'Honduras',
- capital: 'Tegucigalpa',
- languages: ['Spanish'],
- population: 8576532,
- flag: 'https://restcountries.eu/data/hnd.svg',
- currency: 'Honduran lempira'
- },
- {
- name: 'Hong Kong',
- capital: 'City of Victoria',
- languages: ['English', 'Chinese'],
- population: 7324300,
- flag: 'https://restcountries.eu/data/hkg.svg',
- currency: 'Hong Kong dollar'
- },
- {
- name: 'Hungary',
- capital: 'Budapest',
- languages: ['Hungarian'],
- population: 9823000,
- flag: 'https://restcountries.eu/data/hun.svg',
- currency: 'Hungarian forint'
- },
- {
- name: 'Iceland',
- capital: 'Reykjavík',
- languages: ['Icelandic'],
- population: 334300,
- flag: 'https://restcountries.eu/data/isl.svg',
- currency: 'Icelandic króna'
- },
- {
- name: 'India',
- capital: 'New Delhi',
- languages: ['Hindi', 'English'],
- population: 1295210000,
- flag: 'https://restcountries.eu/data/ind.svg',
- currency: 'Indian rupee'
- },
- {
- name: 'Indonesia',
- capital: 'Jakarta',
- languages: ['Indonesian'],
- population: 258705000,
- flag: 'https://restcountries.eu/data/idn.svg',
- currency: 'Indonesian rupiah'
- },
- {
- name: "Côte d'Ivoire",
- capital: 'Yamoussoukro',
- languages: ['French'],
- population: 22671331,
- flag: 'https://restcountries.eu/data/civ.svg',
- currency: 'West African CFA franc'
- },
- {
- name: 'Iran (Islamic Republic of)',
- capital: 'Tehran',
- languages: ['Persian (Farsi)'],
- population: 79369900,
- flag: 'https://restcountries.eu/data/irn.svg',
- currency: 'Iranian rial'
- },
- {
- name: 'Iraq',
- capital: 'Baghdad',
- languages: ['Arabic', 'Kurdish'],
- population: 37883543,
- flag: 'https://restcountries.eu/data/irq.svg',
- currency: 'Iraqi dinar'
- },
- {
- name: 'Ireland',
- capital: 'Dublin',
- languages: ['Irish', 'English'],
- population: 6378000,
- flag: 'https://restcountries.eu/data/irl.svg',
- currency: 'Euro'
- },
- {
- name: 'Isle of Man',
- capital: 'Douglas',
- languages: ['English', 'Manx'],
- population: 84497,
- flag: 'https://restcountries.eu/data/imn.svg',
- currency: 'British pound'
- },
- {
- name: 'Israel',
- capital: 'Jerusalem',
- languages: ['Hebrew (modern)', 'Arabic'],
- population: 8527400,
- flag: 'https://restcountries.eu/data/isr.svg',
- currency: 'Israeli new shekel'
- },
- {
- name: 'Italy',
- capital: 'Rome',
- languages: ['Italian'],
- population: 60665551,
- flag: 'https://restcountries.eu/data/ita.svg',
- currency: 'Euro'
- },
- {
- name: 'Jamaica',
- capital: 'Kingston',
- languages: ['English'],
- population: 2723246,
- flag: 'https://restcountries.eu/data/jam.svg',
- currency: 'Jamaican dollar'
- },
- {
- name: 'Japan',
- capital: 'Tokyo',
- languages: ['Japanese'],
- population: 126960000,
- flag: 'https://restcountries.eu/data/jpn.svg',
- currency: 'Japanese yen'
- },
- {
- name: 'Jersey',
- capital: 'Saint Helier',
- languages: ['English', 'French'],
- population: 100800,
- flag: 'https://restcountries.eu/data/jey.svg',
- currency: 'British pound'
- },
- {
- name: 'Jordan',
- capital: 'Amman',
- languages: ['Arabic'],
- population: 9531712,
- flag: 'https://restcountries.eu/data/jor.svg',
- currency: 'Jordanian dinar'
- },
- {
- name: 'Kazakhstan',
- capital: 'Astana',
- languages: ['Kazakh', 'Russian'],
- population: 17753200,
- flag: 'https://restcountries.eu/data/kaz.svg',
- currency: 'Kazakhstani tenge'
- },
- {
- name: 'Kenya',
- capital: 'Nairobi',
- languages: ['English', 'Swahili'],
- population: 47251000,
- flag: 'https://restcountries.eu/data/ken.svg',
- currency: 'Kenyan shilling'
- },
- {
- name: 'Kiribati',
- capital: 'South Tarawa',
- languages: ['English'],
- population: 113400,
- flag: 'https://restcountries.eu/data/kir.svg',
- currency: 'Australian dollar'
- },
- {
- name: 'Kuwait',
- capital: 'Kuwait City',
- languages: ['Arabic'],
- population: 4183658,
- flag: 'https://restcountries.eu/data/kwt.svg',
- currency: 'Kuwaiti dinar'
- },
- {
- name: 'Kyrgyzstan',
- capital: 'Bishkek',
- languages: ['Kyrgyz', 'Russian'],
- population: 6047800,
- flag: 'https://restcountries.eu/data/kgz.svg',
- currency: 'Kyrgyzstani som'
- },
- {
- name: "Lao People's Democratic Republic",
- capital: 'Vientiane',
- languages: ['Lao'],
- population: 6492400,
- flag: 'https://restcountries.eu/data/lao.svg',
- currency: 'Lao kip'
- },
- {
- name: 'Latvia',
- capital: 'Riga',
- languages: ['Latvian'],
- population: 1961600,
- flag: 'https://restcountries.eu/data/lva.svg',
- currency: 'Euro'
- },
- {
- name: 'Lebanon',
- capital: 'Beirut',
- languages: ['Arabic', 'French'],
- population: 5988000,
- flag: 'https://restcountries.eu/data/lbn.svg',
- currency: 'Lebanese pound'
- },
- {
- name: 'Lesotho',
- capital: 'Maseru',
- languages: ['English', 'Southern Sotho'],
- population: 1894194,
- flag: 'https://restcountries.eu/data/lso.svg',
- currency: 'Lesotho loti'
- },
- {
- name: 'Liberia',
- capital: 'Monrovia',
- languages: ['English'],
- population: 4615000,
- flag: 'https://restcountries.eu/data/lbr.svg',
- currency: 'Liberian dollar'
- },
- {
- name: 'Libya',
- capital: 'Tripoli',
- languages: ['Arabic'],
- population: 6385000,
- flag: 'https://restcountries.eu/data/lby.svg',
- currency: 'Libyan dinar'
- },
- {
- name: 'Liechtenstein',
- capital: 'Vaduz',
- languages: ['German'],
- population: 37623,
- flag: 'https://restcountries.eu/data/lie.svg',
- currency: 'Swiss franc'
- },
- {
- name: 'Lithuania',
- capital: 'Vilnius',
- languages: ['Lithuanian'],
- population: 2872294,
- flag: 'https://restcountries.eu/data/ltu.svg',
- currency: 'Euro'
- },
- {
- name: 'Luxembourg',
- capital: 'Luxembourg',
- languages: ['French', 'German', 'Luxembourgish'],
- population: 576200,
- flag: 'https://restcountries.eu/data/lux.svg',
- currency: 'Euro'
- },
- {
- name: 'Macao',
- capital: '',
- languages: ['Chinese', 'Portuguese'],
- population: 649100,
- flag: 'https://restcountries.eu/data/mac.svg',
- currency: 'Macanese pataca'
- },
- {
- name: 'Macedonia (the former Yugoslav Republic of)',
- capital: 'Skopje',
- languages: ['Macedonian'],
- population: 2058539,
- flag: 'https://restcountries.eu/data/mkd.svg',
- currency: 'Macedonian denar'
- },
- {
- name: 'Madagascar',
- capital: 'Antananarivo',
- languages: ['French', 'Malagasy'],
- population: 22434363,
- flag: 'https://restcountries.eu/data/mdg.svg',
- currency: 'Malagasy ariary'
- },
- {
- name: 'Malawi',
- capital: 'Lilongwe',
- languages: ['English', 'Chichewa'],
- population: 16832910,
- flag: 'https://restcountries.eu/data/mwi.svg',
- currency: 'Malawian kwacha'
- },
- {
- name: 'Malaysia',
- capital: 'Kuala Lumpur',
- languages: ['Malaysian'],
- population: 31405416,
- flag: 'https://restcountries.eu/data/mys.svg',
- currency: 'Malaysian ringgit'
- },
- {
- name: 'Maldives',
- capital: 'Malé',
- languages: ['Divehi'],
- population: 344023,
- flag: 'https://restcountries.eu/data/mdv.svg',
- currency: 'Maldivian rufiyaa'
- },
- {
- name: 'Mali',
- capital: 'Bamako',
- languages: ['French'],
- population: 18135000,
- flag: 'https://restcountries.eu/data/mli.svg',
- currency: 'West African CFA franc'
- },
- {
- name: 'Malta',
- capital: 'Valletta',
- languages: ['Maltese', 'English'],
- population: 425384,
- flag: 'https://restcountries.eu/data/mlt.svg',
- currency: 'Euro'
- },
- {
- name: 'Marshall Islands',
- capital: 'Majuro',
- languages: ['English', 'Marshallese'],
- population: 54880,
- flag: 'https://restcountries.eu/data/mhl.svg',
- currency: 'United States dollar'
- },
- {
- name: 'Martinique',
- capital: 'Fort-de-France',
- languages: ['French'],
- population: 378243,
- flag: 'https://restcountries.eu/data/mtq.svg',
- currency: 'Euro'
- },
- {
- name: 'Mauritania',
- capital: 'Nouakchott',
- languages: ['Arabic'],
- population: 3718678,
- flag: 'https://restcountries.eu/data/mrt.svg',
- currency: 'Mauritanian ouguiya'
- },
- {
- name: 'Mauritius',
- capital: 'Port Louis',
- languages: ['English'],
- population: 1262879,
- flag: 'https://restcountries.eu/data/mus.svg',
- currency: 'Mauritian rupee'
- },
- {
- name: 'Mayotte',
- capital: 'Mamoudzou',
- languages: ['French'],
- population: 226915,
- flag: 'https://restcountries.eu/data/myt.svg',
- currency: 'Euro'
- },
- {
- name: 'Mexico',
- capital: 'Mexico City',
- languages: ['Spanish'],
- population: 122273473,
- flag: 'https://restcountries.eu/data/mex.svg',
- currency: 'Mexican peso'
- },
- {
- name: 'Micronesia (Federated States of)',
- capital: 'Palikir',
- languages: ['English'],
- population: 102800,
- flag: 'https://restcountries.eu/data/fsm.svg',
- currency: '[D]'
- },
- {
- name: 'Moldova (Republic of)',
- capital: 'Chișinău',
- languages: ['Romanian'],
- population: 3553100,
- flag: 'https://restcountries.eu/data/mda.svg',
- currency: 'Moldovan leu'
- },
- {
- name: 'Monaco',
- capital: 'Monaco',
- languages: ['French'],
- population: 38400,
- flag: 'https://restcountries.eu/data/mco.svg',
- currency: 'Euro'
- },
- {
- name: 'Mongolia',
- capital: 'Ulan Bator',
- languages: ['Mongolian'],
- population: 3093100,
- flag: 'https://restcountries.eu/data/mng.svg',
- currency: 'Mongolian tögrög'
- },
- {
- name: 'Montenegro',
- capital: 'Podgorica',
- languages: ['Serbian', 'Bosnian', 'Albanian', 'Croatian'],
- population: 621810,
- flag: 'https://restcountries.eu/data/mne.svg',
- currency: 'Euro'
- },
- {
- name: 'Montserrat',
- capital: 'Plymouth',
- languages: ['English'],
- population: 4922,
- flag: 'https://restcountries.eu/data/msr.svg',
- currency: 'East Caribbean dollar'
- },
- {
- name: 'Morocco',
- capital: 'Rabat',
- languages: ['Arabic'],
- population: 33337529,
- flag: 'https://restcountries.eu/data/mar.svg',
- currency: 'Moroccan dirham'
- },
- {
- name: 'Mozambique',
- capital: 'Maputo',
- languages: ['Portuguese'],
- population: 26423700,
- flag: 'https://restcountries.eu/data/moz.svg',
- currency: 'Mozambican metical'
- },
- {
- name: 'Myanmar',
- capital: 'Naypyidaw',
- languages: ['Burmese'],
- population: 51419420,
- flag: 'https://restcountries.eu/data/mmr.svg',
- currency: 'Burmese kyat'
- },
- {
- name: 'Namibia',
- capital: 'Windhoek',
- languages: ['English', 'Afrikaans'],
- population: 2324388,
- flag: 'https://restcountries.eu/data/nam.svg',
- currency: 'Namibian dollar'
- },
- {
- name: 'Nauru',
- capital: 'Yaren',
- languages: ['English', 'Nauruan'],
- population: 10084,
- flag: 'https://restcountries.eu/data/nru.svg',
- currency: 'Australian dollar'
- },
- {
- name: 'Nepal',
- capital: 'Kathmandu',
- languages: ['Nepali'],
- population: 28431500,
- flag: 'https://restcountries.eu/data/npl.svg',
- currency: 'Nepalese rupee'
- },
- {
- name: 'Netherlands',
- capital: 'Amsterdam',
- languages: ['Dutch'],
- population: 17019800,
- flag: 'https://restcountries.eu/data/nld.svg',
- currency: 'Euro'
- },
- {
- name: 'New Caledonia',
- capital: 'Nouméa',
- languages: ['French'],
- population: 268767,
- flag: 'https://restcountries.eu/data/ncl.svg',
- currency: 'CFP franc'
- },
- {
- name: 'New Zealand',
- capital: 'Wellington',
- languages: ['English', 'Māori'],
- population: 4697854,
- flag: 'https://restcountries.eu/data/nzl.svg',
- currency: 'New Zealand dollar'
- },
- {
- name: 'Nicaragua',
- capital: 'Managua',
- languages: ['Spanish'],
- population: 6262703,
- flag: 'https://restcountries.eu/data/nic.svg',
- currency: 'Nicaraguan córdoba'
- },
- {
- name: 'Niger',
- capital: 'Niamey',
- languages: ['French'],
- population: 20715000,
- flag: 'https://restcountries.eu/data/ner.svg',
- currency: 'West African CFA franc'
- },
- {
- name: 'Nigeria',
- capital: 'Abuja',
- languages: ['English'],
- population: 186988000,
- flag: 'https://restcountries.eu/data/nga.svg',
- currency: 'Nigerian naira'
- },
- {
- name: 'Niue',
- capital: 'Alofi',
- languages: ['English'],
- population: 1470,
- flag: 'https://restcountries.eu/data/niu.svg',
- currency: 'New Zealand dollar'
- },
- {
- name: 'Norfolk Island',
- capital: 'Kingston',
- languages: ['English'],
- population: 2302,
- flag: 'https://restcountries.eu/data/nfk.svg',
- currency: 'Australian dollar'
- },
- {
- name: "Korea (Democratic People's Republic of)",
- capital: 'Pyongyang',
- languages: ['Korean'],
- population: 25281000,
- flag: 'https://restcountries.eu/data/prk.svg',
- currency: 'North Korean won'
- },
- {
- name: 'Northern Mariana Islands',
- capital: 'Saipan',
- languages: ['English', 'Chamorro'],
- population: 56940,
- flag: 'https://restcountries.eu/data/mnp.svg',
- currency: 'United States dollar'
- },
- {
- name: 'Norway',
- capital: 'Oslo',
- languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'],
- population: 5223256,
- flag: 'https://restcountries.eu/data/nor.svg',
- currency: 'Norwegian krone'
- },
- {
- name: 'Oman',
- capital: 'Muscat',
- languages: ['Arabic'],
- population: 4420133,
- flag: 'https://restcountries.eu/data/omn.svg',
- currency: 'Omani rial'
- },
- {
- name: 'Pakistan',
- capital: 'Islamabad',
- languages: ['English', 'Urdu'],
- population: 194125062,
- flag: 'https://restcountries.eu/data/pak.svg',
- currency: 'Pakistani rupee'
- },
- {
- name: 'Palau',
- capital: 'Ngerulmud',
- languages: ['English'],
- population: 17950,
- flag: 'https://restcountries.eu/data/plw.svg',
- currency: '[E]'
- },
- {
- name: 'Palestine, State of',
- capital: 'Ramallah',
- languages: ['Arabic'],
- population: 4682467,
- flag: 'https://restcountries.eu/data/pse.svg',
- currency: 'Israeli new sheqel'
- },
- {
- name: 'Panama',
- capital: 'Panama City',
- languages: ['Spanish'],
- population: 3814672,
- flag: 'https://restcountries.eu/data/pan.svg',
- currency: 'Panamanian balboa'
- },
- {
- name: 'Papua New Guinea',
- capital: 'Port Moresby',
- languages: ['English'],
- population: 8083700,
- flag: 'https://restcountries.eu/data/png.svg',
- currency: 'Papua New Guinean kina'
- },
- {
- name: 'Paraguay',
- capital: 'Asunción',
- languages: ['Spanish', 'Guaraní'],
- population: 6854536,
- flag: 'https://restcountries.eu/data/pry.svg',
- currency: 'Paraguayan guaraní'
- },
- {
- name: 'Peru',
- capital: 'Lima',
- languages: ['Spanish'],
- population: 31488700,
- flag: 'https://restcountries.eu/data/per.svg',
- currency: 'Peruvian sol'
- },
- {
- name: 'Philippines',
- capital: 'Manila',
- languages: ['English'],
- population: 103279800,
- flag: 'https://restcountries.eu/data/phl.svg',
- currency: 'Philippine peso'
- },
- {
- name: 'Pitcairn',
- capital: 'Adamstown',
- languages: ['English'],
- population: 56,
- flag: 'https://restcountries.eu/data/pcn.svg',
- currency: 'New Zealand dollar'
- },
- {
- name: 'Poland',
- capital: 'Warsaw',
- languages: ['Polish'],
- population: 38437239,
- flag: 'https://restcountries.eu/data/pol.svg',
- currency: 'Polish złoty'
- },
- {
- name: 'Portugal',
- capital: 'Lisbon',
- languages: ['Portuguese'],
- population: 10374822,
- flag: 'https://restcountries.eu/data/prt.svg',
- currency: 'Euro'
- },
- {
- name: 'Puerto Rico',
- capital: 'San Juan',
- languages: ['Spanish', 'English'],
- population: 3474182,
- flag: 'https://restcountries.eu/data/pri.svg',
- currency: 'United States dollar'
- },
- {
- name: 'Qatar',
- capital: 'Doha',
- languages: ['Arabic'],
- population: 2587564,
- flag: 'https://restcountries.eu/data/qat.svg',
- currency: 'Qatari riyal'
- },
- {
- name: 'Republic of Kosovo',
- capital: 'Pristina',
- languages: ['Albanian', 'Serbian'],
- population: 1733842,
- flag: 'https://restcountries.eu/data/kos.svg',
- currency: 'Euro'
- },
- {
- name: 'Réunion',
- capital: 'Saint-Denis',
- languages: ['French'],
- population: 840974,
- flag: 'https://restcountries.eu/data/reu.svg',
- currency: 'Euro'
- },
- {
- name: 'Romania',
- capital: 'Bucharest',
- languages: ['Romanian'],
- population: 19861408,
- flag: 'https://restcountries.eu/data/rou.svg',
- currency: 'Romanian leu'
- },
- {
- name: 'Russian Federation',
- capital: 'Moscow',
- languages: ['Russian'],
- population: 146599183,
- flag: 'https://restcountries.eu/data/rus.svg',
- currency: 'Russian ruble'
- },
- {
- name: 'Rwanda',
- capital: 'Kigali',
- languages: ['Kinyarwanda', 'English', 'French'],
- population: 11553188,
- flag: 'https://restcountries.eu/data/rwa.svg',
- currency: 'Rwandan franc'
- },
- {
- name: 'Saint Barthélemy',
- capital: 'Gustavia',
- languages: ['French'],
- population: 9417,
- flag: 'https://restcountries.eu/data/blm.svg',
- currency: 'Euro'
- },
- {
- name: 'Saint Helena, Ascension and Tristan da Cunha',
- capital: 'Jamestown',
- languages: ['English'],
- population: 4255,
- flag: 'https://restcountries.eu/data/shn.svg',
- currency: 'Saint Helena pound'
- },
- {
- name: 'Saint Kitts and Nevis',
- capital: 'Basseterre',
- languages: ['English'],
- population: 46204,
- flag: 'https://restcountries.eu/data/kna.svg',
- currency: 'East Caribbean dollar'
- },
- {
- name: 'Saint Lucia',
- capital: 'Castries',
- languages: ['English'],
- population: 186000,
- flag: 'https://restcountries.eu/data/lca.svg',
- currency: 'East Caribbean dollar'
- },
- {
- name: 'Saint Martin (French part)',
- capital: 'Marigot',
- languages: ['English', 'French', 'Dutch'],
- population: 36979,
- flag: 'https://restcountries.eu/data/maf.svg',
- currency: 'Euro'
- },
- {
- name: 'Saint Pierre and Miquelon',
- capital: 'Saint-Pierre',
- languages: ['French'],
- population: 6069,
- flag: 'https://restcountries.eu/data/spm.svg',
- currency: 'Euro'
- },
- {
- name: 'Saint Vincent and the Grenadines',
- capital: 'Kingstown',
- languages: ['English'],
- population: 109991,
- flag: 'https://restcountries.eu/data/vct.svg',
- currency: 'East Caribbean dollar'
- },
- {
- name: 'Samoa',
- capital: 'Apia',
- languages: ['Samoan', 'English'],
- population: 194899,
- flag: 'https://restcountries.eu/data/wsm.svg',
- currency: 'Samoan tālā'
- },
- {
- name: 'San Marino',
- capital: 'City of San Marino',
- languages: ['Italian'],
- population: 33005,
- flag: 'https://restcountries.eu/data/smr.svg',
- currency: 'Euro'
- },
- {
- name: 'Sao Tome and Principe',
- capital: 'São Tomé',
- languages: ['Portuguese'],
- population: 187356,
- flag: 'https://restcountries.eu/data/stp.svg',
- currency: 'São Tomé and Príncipe dobra'
- },
- {
- name: 'Saudi Arabia',
- capital: 'Riyadh',
- languages: ['Arabic'],
- population: 32248200,
- flag: 'https://restcountries.eu/data/sau.svg',
- currency: 'Saudi riyal'
- },
- {
- name: 'Senegal',
- capital: 'Dakar',
- languages: ['French'],
- population: 14799859,
- flag: 'https://restcountries.eu/data/sen.svg',
- currency: 'West African CFA franc'
- },
- {
- name: 'Serbia',
- capital: 'Belgrade',
- languages: ['Serbian'],
- population: 7076372,
- flag: 'https://restcountries.eu/data/srb.svg',
- currency: 'Serbian dinar'
- },
- {
- name: 'Seychelles',
- capital: 'Victoria',
- languages: ['French', 'English'],
- population: 91400,
- flag: 'https://restcountries.eu/data/syc.svg',
- currency: 'Seychellois rupee'
- },
- {
- name: 'Sierra Leone',
- capital: 'Freetown',
- languages: ['English'],
- population: 7075641,
- flag: 'https://restcountries.eu/data/sle.svg',
- currency: 'Sierra Leonean leone'
- },
- {
- name: 'Singapore',
- capital: 'Singapore',
- languages: ['English', 'Malay', 'Tamil', 'Chinese'],
- population: 5535000,
- flag: 'https://restcountries.eu/data/sgp.svg',
- currency: 'Brunei dollar'
- },
- {
- name: 'Sint Maarten (Dutch part)',
- capital: 'Philipsburg',
- languages: ['Dutch', 'English'],
- population: 38247,
- flag: 'https://restcountries.eu/data/sxm.svg',
- currency: 'Netherlands Antillean guilder'
- },
- {
- name: 'Slovakia',
- capital: 'Bratislava',
- languages: ['Slovak'],
- population: 5426252,
- flag: 'https://restcountries.eu/data/svk.svg',
- currency: 'Euro'
- },
- {
- name: 'Slovenia',
- capital: 'Ljubljana',
- languages: ['Slovene'],
- population: 2064188,
- flag: 'https://restcountries.eu/data/svn.svg',
- currency: 'Euro'
- },
- {
- name: 'Solomon Islands',
- capital: 'Honiara',
- languages: ['English'],
- population: 642000,
- flag: 'https://restcountries.eu/data/slb.svg',
- currency: 'Solomon Islands dollar'
- },
- {
- name: 'Somalia',
- capital: 'Mogadishu',
- languages: ['Somali', 'Arabic'],
- population: 11079000,
- flag: 'https://restcountries.eu/data/som.svg',
- currency: 'Somali shilling'
- },
- {
- name: 'South Africa',
- capital: 'Pretoria',
- languages: [
- 'Afrikaans',
- 'English',
- 'Southern Ndebele',
- 'Southern Sotho',
- 'Swati',
- 'Tswana',
- 'Tsonga',
- 'Venda',
- 'Xhosa',
- 'Zulu'
- ],
- population: 55653654,
- flag: 'https://restcountries.eu/data/zaf.svg',
- currency: 'South African rand'
- },
- {
- name: 'South Georgia and the South Sandwich Islands',
- capital: 'King Edward Point',
- languages: ['English'],
- population: 30,
- flag: 'https://restcountries.eu/data/sgs.svg',
- currency: 'British pound'
- },
- {
- name: 'Korea (Republic of)',
- capital: 'Seoul',
- languages: ['Korean'],
- population: 50801405,
- flag: 'https://restcountries.eu/data/kor.svg',
- currency: 'South Korean won'
- },
- {
- name: 'South Sudan',
- capital: 'Juba',
- languages: ['English'],
- population: 12131000,
- flag: 'https://restcountries.eu/data/ssd.svg',
- currency: 'South Sudanese pound'
- },
- {
- name: 'Spain',
- capital: 'Madrid',
- languages: ['Spanish'],
- population: 46438422,
- flag: 'https://restcountries.eu/data/esp.svg',
- currency: 'Euro'
- },
- {
- name: 'Sri Lanka',
- capital: 'Colombo',
- languages: ['Sinhalese', 'Tamil'],
- population: 20966000,
- flag: 'https://restcountries.eu/data/lka.svg',
- currency: 'Sri Lankan rupee'
- },
- {
- name: 'Sudan',
- capital: 'Khartoum',
- languages: ['Arabic', 'English'],
- population: 39598700,
- flag: 'https://restcountries.eu/data/sdn.svg',
- currency: 'Sudanese pound'
- },
- {
- name: 'Suriname',
- capital: 'Paramaribo',
- languages: ['Dutch'],
- population: 541638,
- flag: 'https://restcountries.eu/data/sur.svg',
- currency: 'Surinamese dollar'
- },
- {
- name: 'Svalbard and Jan Mayen',
- capital: 'Longyearbyen',
- languages: ['Norwegian'],
- population: 2562,
- flag: 'https://restcountries.eu/data/sjm.svg',
- currency: 'Norwegian krone'
- },
- {
- name: 'Swaziland',
- capital: 'Lobamba',
- languages: ['English', 'Swati'],
- population: 1132657,
- flag: 'https://restcountries.eu/data/swz.svg',
- currency: 'Swazi lilangeni'
- },
- {
- name: 'Sweden',
- capital: 'Stockholm',
- languages: ['Swedish'],
- population: 9894888,
- flag: 'https://restcountries.eu/data/swe.svg',
- currency: 'Swedish krona'
- },
- {
- name: 'Switzerland',
- capital: 'Bern',
- languages: ['German', 'French', 'Italian'],
- population: 8341600,
- flag: 'https://restcountries.eu/data/che.svg',
- currency: 'Swiss franc'
- },
- {
- name: 'Syrian Arab Republic',
- capital: 'Damascus',
- languages: ['Arabic'],
- population: 18564000,
- flag: 'https://restcountries.eu/data/syr.svg',
- currency: 'Syrian pound'
- },
- {
- name: 'Taiwan',
- capital: 'Taipei',
- languages: ['Chinese'],
- population: 23503349,
- flag: 'https://restcountries.eu/data/twn.svg',
- currency: 'New Taiwan dollar'
- },
- {
- name: 'Tajikistan',
- capital: 'Dushanbe',
- languages: ['Tajik', 'Russian'],
- population: 8593600,
- flag: 'https://restcountries.eu/data/tjk.svg',
- currency: 'Tajikistani somoni'
- },
- {
- name: 'Tanzania, United Republic of',
- capital: 'Dodoma',
- languages: ['Swahili', 'English'],
- population: 55155000,
- flag: 'https://restcountries.eu/data/tza.svg',
- currency: 'Tanzanian shilling'
- },
- {
- name: 'Thailand',
- capital: 'Bangkok',
- languages: ['Thai'],
- population: 65327652,
- flag: 'https://restcountries.eu/data/tha.svg',
- currency: 'Thai baht'
- },
- {
- name: 'Timor-Leste',
- capital: 'Dili',
- languages: ['Portuguese'],
- population: 1167242,
- flag: 'https://restcountries.eu/data/tls.svg',
- currency: 'United States dollar'
- },
- {
- name: 'Togo',
- capital: 'Lomé',
- languages: ['French'],
- population: 7143000,
- flag: 'https://restcountries.eu/data/tgo.svg',
- currency: 'West African CFA franc'
- },
- {
- name: 'Tokelau',
- capital: 'Fakaofo',
- languages: ['English'],
- population: 1411,
- flag: 'https://restcountries.eu/data/tkl.svg',
- currency: 'New Zealand dollar'
- },
- {
- name: 'Tonga',
- capital: "Nuku'alofa",
- languages: ['English', 'Tonga (Tonga Islands)'],
- population: 103252,
- flag: 'https://restcountries.eu/data/ton.svg',
- currency: 'Tongan paʻanga'
- },
- {
- name: 'Trinidad and Tobago',
- capital: 'Port of Spain',
- languages: ['English'],
- population: 1349667,
- flag: 'https://restcountries.eu/data/tto.svg',
- currency: 'Trinidad and Tobago dollar'
- },
- {
- name: 'Tunisia',
- capital: 'Tunis',
- languages: ['Arabic'],
- population: 11154400,
- flag: 'https://restcountries.eu/data/tun.svg',
- currency: 'Tunisian dinar'
- },
- {
- name: 'Turkey',
- capital: 'Ankara',
- languages: ['Turkish'],
- population: 78741053,
- flag: 'https://restcountries.eu/data/tur.svg',
- currency: 'Turkish lira'
- },
- {
- name: 'Turkmenistan',
- capital: 'Ashgabat',
- languages: ['Turkmen', 'Russian'],
- population: 4751120,
- flag: 'https://restcountries.eu/data/tkm.svg',
- currency: 'Turkmenistan manat'
- },
- {
- name: 'Turks and Caicos Islands',
- capital: 'Cockburn Town',
- languages: ['English'],
- population: 31458,
- flag: 'https://restcountries.eu/data/tca.svg',
- currency: 'United States dollar'
- },
- {
- name: 'Tuvalu',
- capital: 'Funafuti',
- languages: ['English'],
- population: 10640,
- flag: 'https://restcountries.eu/data/tuv.svg',
- currency: 'Australian dollar'
- },
- {
- name: 'Uganda',
- capital: 'Kampala',
- languages: ['English', 'Swahili'],
- population: 33860700,
- flag: 'https://restcountries.eu/data/uga.svg',
- currency: 'Ugandan shilling'
- },
- {
- name: 'Ukraine',
- capital: 'Kiev',
- languages: ['Ukrainian'],
- population: 42692393,
- flag: 'https://restcountries.eu/data/ukr.svg',
- currency: 'Ukrainian hryvnia'
- },
- {
- name: 'United Arab Emirates',
- capital: 'Abu Dhabi',
- languages: ['Arabic'],
- population: 9856000,
- flag: 'https://restcountries.eu/data/are.svg',
- currency: 'United Arab Emirates dirham'
- },
- {
- name: 'United Kingdom of Great Britain and Northern Ireland',
- capital: 'London',
- languages: ['English'],
- population: 65110000,
- flag: 'https://restcountries.eu/data/gbr.svg',
- currency: 'British pound'
- },
- {
- name: 'United States of America',
- capital: 'Washington, D.C.',
- languages: ['English'],
- population: 323947000,
- flag: 'https://restcountries.eu/data/usa.svg',
- currency: 'United States dollar'
- },
- {
- name: 'Uruguay',
- capital: 'Montevideo',
- languages: ['Spanish'],
- population: 3480222,
- flag: 'https://restcountries.eu/data/ury.svg',
- currency: 'Uruguayan peso'
- },
- {
- name: 'Uzbekistan',
- capital: 'Tashkent',
- languages: ['Uzbek', 'Russian'],
- population: 31576400,
- flag: 'https://restcountries.eu/data/uzb.svg',
- currency: "Uzbekistani so'm"
- },
- {
- name: 'Vanuatu',
- capital: 'Port Vila',
- languages: ['Bislama', 'English', 'French'],
- population: 277500,
- flag: 'https://restcountries.eu/data/vut.svg',
- currency: 'Vanuatu vatu'
- },
- {
- name: 'Venezuela (Bolivarian Republic of)',
- capital: 'Caracas',
- languages: ['Spanish'],
- population: 31028700,
- flag: 'https://restcountries.eu/data/ven.svg',
- currency: 'Venezuelan bolívar'
- },
- {
- name: 'Viet Nam',
- capital: 'Hanoi',
- languages: ['Vietnamese'],
- population: 92700000,
- flag: 'https://restcountries.eu/data/vnm.svg',
- currency: 'Vietnamese đồng'
- },
- {
- name: 'Wallis and Futuna',
- capital: 'Mata-Utu',
- languages: ['French'],
- population: 11750,
- flag: 'https://restcountries.eu/data/wlf.svg',
- currency: 'CFP franc'
- },
- {
- name: 'Western Sahara',
- capital: 'El Aaiún',
- languages: ['Spanish'],
- population: 510713,
- flag: 'https://restcountries.eu/data/esh.svg',
- currency: 'Moroccan dirham'
- },
- {
- name: 'Yemen',
- capital: "Sana'a",
- languages: ['Arabic'],
- population: 27478000,
- flag: 'https://restcountries.eu/data/yem.svg',
- currency: 'Yemeni rial'
- },
- {
- name: 'Zambia',
- capital: 'Lusaka',
- languages: ['English'],
- population: 15933883,
- flag: 'https://restcountries.eu/data/zmb.svg',
- currency: 'Zambian kwacha'
- },
- {
- name: 'Zimbabwe',
- capital: 'Harare',
- languages: ['English', 'Shona', 'Northern Ndebele'],
- population: 14240168,
- flag: 'https://restcountries.eu/data/zwe.svg',
- currency: 'Botswana pula'
- }
-]
\ No newline at end of file
diff --git a/20_JS_Higher_order_functions/higher_order_functions.md b/20_JS_Higher_order_functions/higher_order_functions.md
deleted file mode 100644
index 2bfe1b3..0000000
--- a/20_JS_Higher_order_functions/higher_order_functions.md
+++ /dev/null
@@ -1,487 +0,0 @@
-# Higher Order Function
-
-Higher order functions are functions which take other function as a parameter or return a function as a value. The function passed as a parameter is called callback.
-
-## Callback
-A callback is a function which can be passed as parameter to other function. See the example below.
-
-```
-// a callback function, the name of the function could be any name
-const callback = (n) => {
- return n ** 2
-}
-
-// function that takes other function as a callback
-function cube(callback, n) {
- return callback(n) * n
-}
-
-console.log(cube(callback, 3))
-```
-
-## Returning function
-
-Higher order functions return function as a value
-
-```
-// Higher order function returning an other function
-const higherOrder = n => {
- const doSomething = m => {
- const doWhatEver = t => {
- return 2 * n + 3 * m + t
- }
- return doWhatEver
- }
- return doSomething
-}
-console.log(higherOrder(2)(3)(10))
-```
-
-Let us see were we use call back functions. For instance the forEach method uses call back.
-
-```
-const numbers = [1, 2, 3, 4, 5]
-const sumArray = arr => {
- let sum = 0
- const callback = function(element) {
- sum += element
- }
- arr.forEach(callback)
- return sum
-
-}
-console.log(sumArray(numbers))
-```
-```
-15
-```
-
-The above example can be simplified as follows:
-
-```
-const numbers = [1, 2, 3, 4]
-
-const sumArray = arr => {
- let sum = 0
- arr.forEach(function(element) {
- sum += element
- })
- return sum
-
-}
-console.log(sumArray(numbers))
-```
-```
-15
-```
-
-### Setting time
-
-In JavaScript we can execute some activities in a certain interval of time or we can schedule(wait) for some time to execute some activities.
-
-- setInterval
-- setTimeout
-
-### Setting Interval using a setInterval function
-
-In JavaScript, we use setInterval higher order function to do some activity continuously with in some interval of time. The setInterval global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback will be always called in that interval of time.
-
-```
-// syntax
-function callback() {
- // code goes here
-}
-setInterval(callback, duration)
-```
-```
-function sayHello() {
- console.log('Hello')
-}
-setInterval(sayHello, 1000) // it prints hello in every second, 1000ms is 1s
-```
-
-### Setting a time using a setTimeout
-
-In JavaScript, we use setTimeout higher order function to execute some action at some time in the future. The setTimeout global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback wait for that amount of time.
-
-```
-// syntax
-function callback() {
- // code goes here
-}
-setTimeout(callback, duration) // duration in milliseconds
-```
-```
-function sayHello() {
- console.log('Hello')
-}
-setTimeout(sayHello, 2000) // it prints hello after it waits for 2 seconds.
-```
-
-### Functional Programming
-
-Instead of writing regular loop, latest version of JavaScript introduced lots of built in methods which can help us to solve complicated problems. All builtin methods take callback function. In this section, we will see forEach, map, filter, reduce, find, every, some, and sort.
-
-#### forEach
-
-forEach: Iterate an array elements. We use forEach only with arrays. It takes a callback function with elements, index parameter and array itself. The index and the array optional.
-
-```
-arr.forEach(function (element, index, arr) {
- console.log(index, element, arr)
-})
-// The above code can be written using arrow function
-arr.forEach((element, index, arr) => {
- console.log(index, element, arr)
-})
-// The above code can be written using arrow function and explicit return
-arr.forEach((element, index, arr) => console.log(index, element, arr))
-```
-
-```
-let sum = 0;
-const numbers = [1, 2, 3, 4, 5];
-numbers.forEach(num => console.log(num))
-console.log(sum)
-```
-
-```
-1
-2
-3
-4
-5
-```
-
-```
-let sum = 0;
-const numbers = [1, 2, 3, 4, 5];
-numbers.forEach(num => sum += num)
-
-console.log(sum)
-```
-
-```
-15
-```
-
-```
-const countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland']
-countries.forEach((element) => console.log(element.toUpperCase()))
-```
-
-```
-FINLAND
-DENMARK
-SWEDEN
-NORWAY
-ICELAND
-```
-
-#### map
-
-map: Iterate an array elements and modify the array elements. It takes a callback function with elements, index , array parameter and return a new array.
-```
-const modifiedArray = arr.map(function (element, index, arr) {
- return element
-})
-```
-
-```
-/*Arrow function and explicit return
-const modifiedArray = arr.map((element,index) => element);
-*/
-//Example
-const numbers = [1, 2, 3, 4, 5]
-const numbersSquare = numbers.map((num) => num * num)
-
-console.log(numbersSquare)
-```
-
-```
-[1, 4, 9, 16, 25]
-```
-```
-const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
-const namesToUpperCase = names.map((name) => name.toUpperCase())
-console.log(namesToUpperCase)
-```
-```
-['ASABENEH', 'MATHIAS', 'ELIAS', 'BROOK']
-```
-```
-const countries = [
- 'Albania',
- 'Bolivia',
- 'Canada',
- 'Denmark',
- 'Ethiopia',
- 'Finland',
- 'Germany',
- 'Hungary',
- 'Ireland',
- 'Japan',
- 'Kenya',
-]
-const countriesToUpperCase = countries.map((country) => country.toUpperCase())
-console.log(countriesToUpperCase)
-
-/*
-// Arrow function
-const countriesToUpperCase = countries.map((country) => {
- return country.toUpperCase();
-})
-//Explicit return arrow function
-const countriesToUpperCase = countries.map(country => country.toUpperCase());
-*/
-```
-```
-['ALBANIA', 'BOLIVIA', 'CANADA', 'DENMARK', 'ETHIOPIA', 'FINLAND', 'GERMANY', 'HUNGARY', 'IRELAND', 'JAPAN', 'KENYA']
-```
-
-```
-const countriesFirstThreeLetters = countries.map((country) =>
- country.toUpperCase().slice(0, 3)
-)
-```
-```
- ["ALB", "BOL", "CAN", "DEN", "ETH", "FIN", "GER", "HUN", "IRE", "JAP", "KEN"]
- ```
-
-#### filter
-
-Filter: Filter out items which full fill filtering conditions and return a new array.
-```
-//Filter countries containing land
-const countriesContainingLand = countries.filter((country) =>
- country.includes('land')
-)
-console.log(countriesContainingLand)
-```
-```
-['Finland', 'Ireland']
-```
-
-```
-const countriesEndsByia = countries.filter((country) => country.endsWith('ia'))
-console.log(countriesEndsByia)
-```
-
-```
-['Albania', 'Bolivia','Ethiopia']
-```
-
-```
-const countriesHaveFiveLetters = countries.filter(
- (country) => country.length === 5
-)
-console.log(countriesHaveFiveLetters)
-```
-
-```
-['Japan', 'Kenya']
-```
-
-```
-const scores = [
- { name: 'Asabeneh', score: 95 },
- { name: 'Lidiya', score: 98 },
- { name: 'Mathias', score: 80 },
- { name: 'Elias', score: 50 },
- { name: 'Martha', score: 85 },
- { name: 'John', score: 100 },
-]
-
-const scoresGreaterEighty = scores.filter((score) => score.score > 80)
-console.log(scoresGreaterEighty)
-```
-```
-[{name: 'Asabeneh', score: 95}, { name: 'Lidiya', score: 98 },{name: 'Martha', score: 85},{name: 'John', score: 100}]
-```
-
-#### reduce
-
-reduce: Reduce takes a callback function. The call back function takes accumulator, current, and optional initial value as a parameter and returns a single value. It is a good practice to define an initial value for the accumulator value. If we do not specify this parameter, by default accumulator will get array first value. If our array is an empty array, then Javascript will throw an error.
-
-```
-arr.reduce((acc, cur) => {
- // some operations goes here before returning a value
- return
-}, initialValue)
-```
-```
-const numbers = [1, 2, 3, 4, 5]
-const sum = numbers.reduce((acc, cur) => acc + cur, 0)
-
-console.log(sum)
-```
-```
-15
-```
-
-#### every
-
-every: Check if all the elements are similar in one aspect. It returns boolean
-
-```
-const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
-const areAllStr = names.every((name) => typeof name === 'string') // Are all strings?
-
-console.log(areAllStr)
-```
-
-```
-true
-```
-
-```
-const bools = [true, true, true, true]
-const areAllTrue = bools.every((b) => b === true) // Are all true?
-
-console.log(areAllTrue) // true
-```
-
-```
-true
-```
-
-#### find
-
-find: Return the first element which satisfies the condition
-
-```
-const ages = [24, 22, 25, 32, 35, 18]
-const age = ages.find((age) => age < 20)
-
-console.log(age)
-```
-
-```
-18
-```
-
-```
-const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
-const result = names.find((name) => name.length > 7)
-console.log(result)
-```
-
-```
-Asabeneh
-```
-
-```
-const scores = [
- { name: 'Asabeneh', score: 95 },
- { name: 'Mathias', score: 80 },
- { name: 'Elias', score: 50 },
- { name: 'Martha', score: 85 },
- { name: 'John', score: 100 },
-]
-
-const score = scores.find((user) => user.score > 80)
-console.log(score)
-```
-
-```
-{ name: "Asabeneh", score: 95 }
-```
-
-#### findIndex
-
-findIndex: Return the position of the first element which satisfies the condition
-
-```
-const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
-const ages = [24, 22, 25, 32, 35, 18]
-
-const result = names.findIndex((name) => name.length > 7)
-console.log(result) // 0
-
-const age = ages.findIndex((age) => age < 20)
-console.log(age) // 5
-```
-
-#### some
-
-some: Check if some of the elements are similar in one aspect. It returns boolean
-
-```
-const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
-const bools = [true, true, true, true]
-
-const areSomeTrue = bools.some((b) => b === true)
-
-console.log(areSomeTrue) //true
-```
-
-```
-const areAllStr = names.some((name) => typeof name === 'number') // Are all strings ?
-console.log(areAllStr) // false
-```
-
-#### sort
-
-sort: The sort methods arranges the array elements either ascending or descending order. By default, the sort() method sorts values as strings.This works well for string array items but not for numbers. If number values are sorted as strings and it give us wrong result. Sort method modify the original array. It is recommended to copy the original data before you start using sort method.
-
-##### Sorting string values
-
-```
-const products = ['Milk', 'Coffee', 'Sugar', 'Honey', 'Apple', 'Carrot']
-console.log(products.sort()) // ['Apple', 'Carrot', 'Coffee', 'Honey', 'Milk', 'Sugar']
-//Now the original products array is also sorted
-```
-
-##### Sorting Numeric values
-
-As you can see in the example below, 100 came first after sorted in ascending order. Sort converts items to string , since '100' and other numbers compared, 1 which the beginning of the string '100' became the smallest. To avoid this, we use a compare call back function inside the sort method, which return a negative, zero or positive.
-
-```
-const numbers = [9.81, 3.14, 100, 37]
-// Using sort method to sort number items provide a wrong result. see below
-console.log(numbers.sort()) //[100, 3.14, 37, 9.81]
-numbers.sort(function (a, b) {
- return a - b
-})
-
-console.log(numbers) // [3.14, 9.81, 37, 100]
-
-numbers.sort(function (a, b) {
- return b - a
-})
-console.log(numbers) //[100, 37, 9.81, 3.14]
-```
-
-##### Sorting Object Arrays
-
-Whenever we sort objects in an array, we use the object key to compare. Let us see the example below.
-
-```
-objArr.sort(function (a, b) {
- if (a.key < b.key) return -1
- if (a.key > b.key) return 1
- return 0
-})
-
-// or
-
-objArr.sort(function (a, b) {
- if (a['key'] < b['key']) return -1
- if (a['key'] > b['key']) return 1
- return 0
-})
-
-const users = [
- { name: 'Asabeneh', age: 150 },
- { name: 'Brook', age: 50 },
- { name: 'Eyob', age: 100 },
- { name: 'Elias', age: 22 },
-]
-users.sort((a, b) => {
- if (a.age < b.age) return -1
- if (a.age > b.age) return 1
- return 0
-})
-console.log(users) // sorted ascending
-// [{…}, {…}, {…}, {…}]
-```
\ No newline at end of file
diff --git a/21_JS_REGULAR_EXPRESSION/Ch21_pro_01.js b/21_JS_REGULAR_EXPRESSION/Ch21_pro_01.js
new file mode 100644
index 0000000..c2809a0
--- /dev/null
+++ b/21_JS_REGULAR_EXPRESSION/Ch21_pro_01.js
@@ -0,0 +1,13 @@
+function is_valid_variable(variableName) {
+ const validVariablePattern = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
+
+ // Test if the variableName matches the pattern
+ return validVariablePattern.test(variableName);
+}
+
+
+
+console.log(is_valid_variable('first_name')); // true
+console.log(is_valid_variable('first-name')); // false
+console.log(is_valid_variable('1first_name')); // false
+console.log(is_valid_variable('firstname')); // true
\ No newline at end of file
diff --git a/21_JS_REGULAR_EXPRESSION/Ch21_pro_02.js b/21_JS_REGULAR_EXPRESSION/Ch21_pro_02.js
new file mode 100644
index 0000000..7d1a3bb
--- /dev/null
+++ b/21_JS_REGULAR_EXPRESSION/Ch21_pro_02.js
@@ -0,0 +1,79 @@
+function tenMostFrequentWords(paragraph, numWords = 10) {
+ // Step 1: Clean the paragraph and split into words
+ const words = paragraph
+ .replace(/[.,]/g, '') // Remove punctuation
+ .split(/\s+/); // Split by whitespace
+
+ // Step 2: Count occurrences of each word
+ const wordCount = {};
+ words.forEach(word => {
+ word = word.toLowerCase(); // Convert to lowercase to handle case insensitivity
+ if (word in wordCount) {
+ wordCount[word]++;
+ } else {
+ wordCount[word] = 1;
+ }
+ });
+
+ // Step 3: Convert to array and sort by count in descending order
+ const sortedWords = Object.keys(wordCount)
+ .map(word => ({ word: word, count: wordCount[word] }))
+ .sort((a, b) => b.count - a.count);
+
+ // Step 4: Return the top `numWords` words
+ return sortedWords.slice(0, numWords);
+}
+
+// Example usage
+const 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.`;
+
+console.log(tenMostFrequentWords(paragraph)); // Default is top 10
+console.log(tenMostFrequentWords(paragraph, 10)); // Explicitly request top 10
+
+
+
+
+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.`
+console.log(tenMostFrequentWords(paragraph))
+
+[
+ {word:'love', count:6},
+ {word:'you', count:5},
+ {word:'can', count:3},
+ {word:'what', count:2},
+ {word:'teaching', count:2},
+ {word:'not', count:2},
+ {word:'else', count:2},
+ {word:'do', count:2},
+ {word:'I', count:2},
+ {word:'which', count:1},
+ {word:'to', count:1},
+ {word:'the', count:1},
+ {word:'something', count:1},
+ {word:'if', count:1},
+ {word:'give', count:1},
+ {word:'develop',count:1},
+ {word:'capabilities',count:1},
+ {word:'application', count:1},
+ {word:'an',count:1},
+ {word:'all',count:1},
+ {word:'Python',count:1},
+ {word:'If',count:1}
+]
+
+
+console.log(tenMostFrequentWords(paragraph, 10))
+
+[{word:'love', count:6},
+ {word:'you', count:5},
+ {word:'can', count:3},
+ {word:'what', count:2},
+ {word:'teaching', count:2},
+ {word:'not', count:2},
+ {word:'else', count:2},
+ {word:'do', count:2},
+ {word:'I', count:2},
+ {word:'which', count:1}
+ ]
+
+
\ No newline at end of file
diff --git a/21_JS_Regular_expressions/Ch21_pgm_01.js b/21_JS_Regular_expressions/Ch21_pgm_01.js
deleted file mode 100644
index cb43ccd..0000000
--- a/21_JS_Regular_expressions/Ch21_pgm_01.js
+++ /dev/null
@@ -1,6 +0,0 @@
-// Write a pattern which identify if a string is a valid JavaScript variable
-
-// is_valid_variable('first_name') # True
-// is_valid_variable('first-name') # False
-// is_valid_variable('1first_name') # False
-// is_valid_variable('firstname') # True
\ No newline at end of file
diff --git a/21_JS_Regular_expressions/Ch21_pgm_02.js b/21_JS_Regular_expressions/Ch21_pgm_02.js
deleted file mode 100644
index 03277ec..0000000
--- a/21_JS_Regular_expressions/Ch21_pgm_02.js
+++ /dev/null
@@ -1,44 +0,0 @@
-// Write a function called tenMostFrequentWords which get the ten most frequent word from a string?
-
-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.`
-console.log(tenMostFrequentWords(paragraph))
-
-[
- {word:'love', count:6},
- {word:'you', count:5},
- {word:'can', count:3},
- {word:'what', count:2},
- {word:'teaching', count:2},
- {word:'not', count:2},
- {word:'else', count:2},
- {word:'do', count:2},
- {word:'I', count:2},
- {word:'which', count:1},
- {word:'to', count:1},
- {word:'the', count:1},
- {word:'something', count:1},
- {word:'if', count:1},
- {word:'give', count:1},
- {word:'develop',count:1},
- {word:'capabilities',count:1},
- {word:'application', count:1},
- {word:'an',count:1},
- {word:'all',count:1},
- {word:'Python',count:1},
- {word:'If',count:1}
-]
-
-
-console.log(tenMostFrequentWords(paragraph, 10))
-
-[{word:'love', count:6},
- {word:'you', count:5},
- {word:'can', count:3},
- {word:'what', count:2},
- {word:'teaching', count:2},
- {word:'not', count:2},
- {word:'else', count:2},
- {word:'do', count:2},
- {word:'I', count:2},
- {word:'which', count:1}
- ]
\ No newline at end of file
diff --git a/21_JS_Regular_expressions/regEx.md b/21_JS_Regular_expressions/regEx.md
deleted file mode 100644
index ddf589d..0000000
--- a/21_JS_Regular_expressions/regEx.md
+++ /dev/null
@@ -1,361 +0,0 @@
-# Regular Expressions
-
-A regular expression or RegExp is a small programming language that helps to find pattern in data. A RegExp can be used to check if some pattern exists in a different data types. To use RegExp in JavaScript either we use RegExp constructor or we can declare a RegExp pattern using two forward slashes followed by a flag. We can create a pattern in two ways.
-
-To declare a string we use a single quote, double quote a backtick to declare a regular expression we use two forward slashes and an optional flag. The flag could be g, i, m, s, u or y.
-
-### RegExp parameters
-
-A regular expression takes two parameters. One required search pattern and an optional flag.
-
-#### Pattern
-
-A pattern could be a text or any form of pattern which some sort of similarity. For instance the word spam in an email could be a pattern we are interested to look for in an email or a phone number format number might be our interest to look for.
-
-#### Flags
-
-Flags are optional parameters in a regular expression which determine the type of searching. Let us see some of the flags:
-
-- g: a global flag which means looking for a pattern in whole text
-- i: case insensitive flag(it searches for both lowercase and uppercase)
-- m: multiline
-
-### Creating a pattern with RegExp Constructor
-
-Declaring regular expression without global flag and case insensitive flag.
-
-```
-// without flag
-let pattern = 'love'
-let regEx = new RegExp(pattern)
-```
-
-Declaring regular expression with global flag and case insensitive flag.
-
-```
-let pattern = 'love'
-let flag = 'gi'
-let regEx = new RegExp(pattern, flag)
-```
-
-Declaring a regex pattern using RegExp object. Writing the pattern and the flag inside the RegExp constructor
-
-```
-let regEx = new RegExp('love','gi')
-```
-
-### Creating a pattern without RegExp Constructor
-
-Declaring regular expression with global flag and case insensitive flag.
-
-```
-let regEx= /love/gi
-```
-
-The above regular expression is the same as the one which we created with RegExp constructor
-
-```
-let regEx= new RegExp('love','gi')
-```
-
-### RegExpp Object Methods
-
-Let us see some of RegExp methods
-
-#### Testing for a match
-
-test():Tests for a match in a string. It returns true or false.
-
-```
-const str = 'I love JavaScript'
-const pattern = /love/
-const result = pattern.test(str)
-console.log(result)
-```
-```
-true
-```
-
-#### Array containing all of the match
-
-match():Returns an array containing all of the matches, including capturing groups, or null if no match is found. If we do not use a global flag, match() returns an array containing the pattern, index, input and group.
-
-```
-const str = 'I love JavaScript'
-const pattern = /love/
-const result = str.match(pattern)
-console.log(result)
-```
-
-```
-["love", index: 2, input: "I love JavaScript", groups: undefined]
-```
-
-```
-const str = 'I love JavaScript'
-const pattern = /love/g
-const result = str.match(pattern)
-console.log(result)
-```
-```
-["love"]
-```
-
-search(): Tests for a match in a string. It returns the index of the match, or -1 if the search fails.
-```
-const str = 'I love JavaScript'
-const pattern = /love/g
-const result = str.search(pattern)
-console.log(result)
-```
-```
-2
-```
-
-#### Replacing a substring
-
-replace(): Executes a search for a match in a string, and replaces the matched substring with a replacement substring.
-
-```
-const txt = 'Python is the most beautiful language that a human begin has ever created.\
-I recommend python for a first programming language'
-
-matchReplaced = txt.replace(/Python|python/, 'JavaScript')
-console.log(matchReplaced)
-```
-
-```
-JavaScript is the most beautiful language that a human begin has ever created.I recommend python for a first programming language
-```
-
-```
-const txt = 'Python is the most beautiful language that a human begin has ever created.\
-I recommend python for a first programming language'
-
-matchReplaced = txt.replace(/Python|python/g, 'JavaScript')
-console.log(matchReplaced)
-```
-```
-JavaScript is the most beautiful language that a human begin has ever created.I recommend JavaScript for a first programming language
-```
-
-```
-const txt = 'Python is the most beautiful language that a human begin has ever created.\
-I recommend python for a first programming language'
-
-matchReplaced = txt.replace(/Python/gi, 'JavaScript')
-console.log(matchReplaced)
-```
-```
-JavaScript is the most beautiful language that a human begin has ever created.I recommend JavaScript for a first programming language
-```
-```
-const txt = '%I a%m te%%a%%che%r% a%n%d %% I l%o%ve te%ach%ing.\
-T%he%re i%s n%o%th%ing as m%ore r%ewarding a%s e%duc%at%i%ng a%n%d e%m%p%ow%er%ing \
-p%e%o%ple.\
-I fo%und te%a%ching m%ore i%n%t%er%%es%ting t%h%an any other %jobs.\
-D%o%es thi%s m%ot%iv%a%te %y%o%u to b%e a t%e%a%cher.'
-
-matches = txt.replace(/%/g, '')
-console.log(matches)
-```
-```
-I am teacher and I love teaching.There is nothing as more rewarding as educating and empowering people.I found teaching more interesting than any other jobs.Does this motivate you to be a teacher.
-```
-
-- []: A set of characters
- - [a-c] means, a or b or c
- - [a-z] means, any letter a to z
- - [A-Z] means, any character A to
- - [0-3] means, 0 or 1 or 2 or 3
- - [0-9] means any number 0 to 9
- - [A-Za-z0-9] any character which is a to z, A to Z, 0 to 9
-- \: uses to escape special characters
- - \d mean: match where the string contains digits (numbers from 0-9)
- - \D mean: match where the string does not contain digits
-- . : any character except new line character(\n)
-- ^: starts with
- - r'^substring' eg r'^love', a sentence which starts with a word love
- - r'[^abc] mean not a, not b, not c.
-- $: ends with
- - r'substring$' eg r'love$', sentence ends with a word love
-- *: zero or more times
- - r'[a]*' means a optional or it can occur many times.
-- +: one or more times
- - r'[a]+' means at least once or more times
-- ?: zero or one times
- - r'[a]?' means zero times or once
-- \b: word bounder, matches with the beginning or ending of a word
-- {3}: Exactly 3 characters
-- {3,}: At least 3 characters
-- {3,8}: 3 to 8 characters
-- |: Either or
- - r'apple|banana' mean either of an apple or a banana
-- (): Capture and group
-
-
-
-Let's use example to clarify the above meta characters
-
-### Square Bracket
-
-Let's use square bracket to include lower and upper case
-
-```
-const pattern = '[Aa]pple' // this square bracket means either A or a
-const txt = 'Apple and banana are fruits. An old cliche says an apple a day keeps the doctor way has been replaced by a banana a day keeps the doctor far far away. '
-const matches = txt.match(pattern)
-
-console.log(matches)
-```
-```
-["Apple", index: 0, input: "Apple and banana are fruits. An old cliche says an apple a day keeps the doctor way has been replaced by a banana a day keeps the doctor far far away.", groups: undefined]
-```
-```
-const pattern = /[Aa]pple/g // this square bracket means either A or a
-const txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. '
-const matches = txt.match(pattern)
-
-console.log(matches)
-```
-```
-["Apple", "apple"]
-```
-
-If we want to look for the banana, we write the pattern as follows:
-
-```
-const pattern = /[Aa]pple|[Bb]anana/g // this square bracket mean either A or a
-const txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. Banana is easy to eat too.'
-const matches = txt.match(pattern)
-
-console.log(matches)
-```
-```
-["Apple", "banana", "apple", "banana", "Banana"]
-```
-
-Using the square bracket and or operator , we manage to extract Apple, apple, Banana and banana.
-
-#### Escape character(\) in RegExp
-
-```
-const pattern = /\d/g // d is a special character which means digits
-const txt = 'This regular expression example was made in January 12, 2020.'
-const matches = txt. match(pattern)
-
-console.log(matches) // ["1", "2", "2", "0", "2", "0"], this is not what we want
-const pattern = /\d+/g // d is a special character which means digits
-const txt = 'This regular expression example was made in January 12, 2020.'
-const matches = txt. match(pattern)
-
-console.log(matches) // ["12", "2020"], this is not what we want
-```
-
-#### One or more times(+)
-
-```
-const pattern = /\d+/g // d is a special character which means digits
-const txt = 'This regular expression example was made in January 12, 2020.'
-const matches = txt. match(pattern)
-console.log(matches) // ["12", "2020"], this is not what we want
-```
-
-#### Period(.)
-
-```
-const pattern = /[a]./g // this square bracket means a and . means any character except new line
-const txt = 'Apple and banana are fruits'
-const matches = txt.match(pattern)
-
-console.log(matches) // ["an", "an", "an", "a ", "ar"]
-```
-```
-const pattern = /[a].+/g // . any character, + any character one or more times
-const txt = 'Apple and banana are fruits'
-const matches = txt.match(pattern)
-
-console.log(matches) // ['and banana are fruits']
-```
-
-#### Zero or more times(*)
-
-Zero or many times. The pattern may not occur or it can occur many times.
-
-```
-const pattern = /[a].*/g //. any character, + any character one or more times
-const txt = 'Apple and banana are fruits'
-const matches = txt.match(pattern)
-
-console.log(matches) // ['and banana are fruits']
-```
-
-#### Zero or one times(?)
-
-Zero or one times. The pattern may not occur or it may occur once.
-
-```
-const txt = 'I am not sure if there is a convention how to write the word e-mail.\
-Some people write it email others may write it as Email or E-mail.'
-const pattern = /[Ee]-?mail/g // ? means optional
-matches = txt.match(pattern)
-
-console.log(matches) // ["e-mail", "email", "Email", "E-mail"]
-```
-
-#### Quantifier in RegExp
-
-We can specify the length of the substring we look for in a text, using a curly bracket. Let us see, how ot use RegExp quantifiers. Imagine, we are interested in substring that their length are 4 characters
-
-```
-const txt = 'This regular expression example was made in December 6, 2019.'
-const pattern = /\\b\w{4}\b/g // exactly four character words
-const matches = txt.match(pattern)
-console.log(matches) //['This', 'made', '2019']
-const txt = 'This regular expression example was made in December 6, 2019.'
-const pattern = /\b[a-zA-Z]{4}\b/g // exactly four character words without numbers
-const matches = txt.match(pattern)
-console.log(matches) //['This', 'made']
-```
-
-```
-const txt = 'This regular expression example was made in December 6, 2019.'
-const pattern = /\d{4}/g // a number and exactly four digits
-const matches = txt.match(pattern)
-console.log(matches) // ['2019']
-```
-```
-const txt = 'This regular expression example was made in December 6, 2019.'
-const pattern = /\d{1,4}/g // 1 to 4
-const matches = txt.match(pattern)
-console.log(matches) // ['6', '2019']
-```
-
-#### Cart ^
-
-Starts with
-```
-const txt = 'This regular expression example was made in December 6, 2019.'
-const pattern = /^This/ // ^ means starts with
-const matches = txt.match(pattern)
-console.log(matches) // ['This']
-```
-
-Negation
-```
-const txt = 'This regular expression example was made in December 6, 2019.'
-const pattern = /[^A-Za-z,. ]+/g // ^ in set character means negation, not A to Z, not a to z, no space, no comma no period
-const matches = txt.match(pattern)
-console.log(matches) // ["6", "2019"]
-```
-
-#### Exact match
-It should have ^ starting and $ which is an end.
-
-```
-let pattern = /^[A-Z][a-z]{3,12}$/;
-let name = 'Asabeneh';
-let result = pattern.test(name)
-
-console.log(result) // true
-```
\ No newline at end of file
diff --git a/22_JS_PROJECT_1/galaxy.gif b/22_JS_PROJECT_1/galaxy.gif
new file mode 100644
index 0000000..3c8aab6
Binary files /dev/null and b/22_JS_PROJECT_1/galaxy.gif differ
diff --git a/22_JS_PROJECT_1/solar_system_project.html b/22_JS_PROJECT_1/solar_system_project.html
new file mode 100644
index 0000000..ed22065
--- /dev/null
+++ b/22_JS_PROJECT_1/solar_system_project.html
@@ -0,0 +1,92 @@
+
+
+
+
+
+ Solar System Weight Calculator
+
+
+
+
+
+