From 8ad6c9568ee98a2395d94e930774d3579f4a118d Mon Sep 17 00:00:00 2001 From: Hedyeh Date: Tue, 26 May 2020 00:07:41 +0100 Subject: [PATCH 1/5] Javascript week4 --- week-4/Homework/mandatory/2-writers.js | 40 +++++-- week-4/Homework/mandatory/3-water-bottle.js | 101 ++++++++++++---- week-4/Homework/mandatory/4-groceries.js | 42 ++++--- .../A-objects-intro/exercise-part-0.js | 11 +- .../A-objects-intro/exercise-part-1.js | 33 ++++++ .../A-objects-intro/exercise-part-2.js | 21 ++-- .../InClass/B-objects-get-set/exercise-1.js | 15 ++- .../InClass/B-objects-get-set/exercise-2.js | 16 +-- .../InClass/B-objects-get-set/exercise-3.js | 6 +- .../InClass/B-objects-get-set/exercise-4.js | 10 +- .../C-more-complex-objects/exercise-1.js | 29 +++-- .../C-more-complex-objects/exercise-2.js | 35 +++--- .../C-more-complex-objects/exercise-3.js | 60 ++++++---- week-4/InClass/D-methods/exercise-1.js | 16 +-- week-4/InClass/D-methods/exercise-2.js | 15 ++- week-4/InClass/D-methods/exercise-3.js | 24 ++-- week-4/InClass/D-methods/exercise-4.js | 14 ++- week-4/InClass/D-methods/exercise-5.js | 70 +++++++----- .../InClass/E-arrays-of-objects/exercise-1.js | 54 +++++---- .../InClass/E-arrays-of-objects/exercise-2.js | 59 ++++++---- .../InClass/E-arrays-of-objects/exercise-3.js | 108 ++++++++++-------- .../InClass/F-object-keys/exercise-part-0.js | 22 ++-- .../InClass/F-object-keys/exercise-part-1.js | 6 +- .../InClass/F-object-keys/exercise-part-2.js | 36 +++--- week-4/InClass/forinLoop.js | 21 +++- 25 files changed, 553 insertions(+), 311 deletions(-) diff --git a/week-4/Homework/mandatory/2-writers.js b/week-4/Homework/mandatory/2-writers.js index 4d4bfebaf..f2964db90 100644 --- a/week-4/Homework/mandatory/2-writers.js +++ b/week-4/Homework/mandatory/2-writers.js @@ -22,29 +22,29 @@ let writers = [ lastName: "Woolf", occupation: "writer", age: 59, - alive: false + alive: false, }, { firstName: "Zadie", lastName: "Smith", occupation: "writer", age: 41, - alive: true + alive: true, }, { firstName: "Jane", lastName: "Austen", occupation: "writer", age: 41, - alive: false + alive: false, }, { firstName: "bell", lastName: "hooks", occupation: "writer", age: 64, - alive: true - } + alive: true, + }, ]; /* @@ -53,19 +53,41 @@ Exercise 1: insert corresponding values to the place holder that are indicated in courle braces: "Hi, my name is {firstName} {lastName}. I am {age} years old, and work as a {occupation}." */ - - +for (let key in writers) + console.log( + `Hi, my name is ${writers[key].firstName} ${writers[key].lastName}. I am ${writers[key].age} years old, and work as a ${writers[key].occupation}.` + ); /* Exercise 2: Only `console.log()` the writers who are in their 40s with us anymore with the sentence:(meaning between 40 and 49) "Writer {firstName} {lastName} died at {age} years old." */ - - +for (let i = 0; i < writers.length; i++) { + if ( + writers[i].age >= 40 && + writers[i].age < 49 && + writers[i].alive === false + ) { + console.log( + `Writer ${writers[i].firstName} ${writers[i].lastName} died at ${writers[i].age} years old.` + ); + } +} /* Exercise 3: Only `console.log()` contemporary writers who are in their forties: "Hi, my name is {firstName} {lastName}. I am {age} years old." */ +for (let i = 0; i < writers.length; i++) { + if ( + writers[i].age >= 40 && + writers[i].age < 49 && + writers[i].alive === true + ) { + console.log( + `Hi,my name is ${writers[i].firstName} ${writers[i].lastName}. I am ${writers[i].age} years old.` + ); + } +} diff --git a/week-4/Homework/mandatory/3-water-bottle.js b/week-4/Homework/mandatory/3-water-bottle.js index 4ad72fdd9..4973ff891 100644 --- a/week-4/Homework/mandatory/3-water-bottle.js +++ b/week-4/Homework/mandatory/3-water-bottle.js @@ -20,21 +20,37 @@ You have to implement the missing features according to the specification. // Here is your starting point: let bottle = { volume: 0, - fillUp: function() { + fillUp: function () { + this.volume = 100; // calling this function should pour your bottle full (volume = 100); }, pour: function () { + if (this.volume < 100) { + return (this.volume += 10); + } // calling this function should increase your bottle volume by 10 unit; }, - drink: function() { + drink: function () { + if (this.volume >= 10) { + return (this.volume -= 10); + } // calling this function should decrease your bottle volume by 10 unit; }, isFull: function () { + if (this.volume == 100) return true; + else { + return false; + } + // this function should return true if your bottle is full; + }, + isEmpty: function () { + if (this.volume == 0) { + return true; + } else { + return false; + } // this function should return true if your bottle is empty; }, - isEmpty: function() { - // this function should return true if your bottle is full; - } }; /* @@ -49,7 +65,7 @@ Extra question: Leave your answer below: */ - +// Because if we use `this` keyword and in the future the name of variable changes, it doesn't need to change the name in every single object. // HERE COMES YOUR ANSWER /* @@ -67,14 +83,23 @@ if (bottle.isFull()) console.log(`That's correct! Bottle is full.`); else console.warn(`Not quite right! Bottle should be full but it is not.`); if (!bottle.isEmpty()) console.log(`That's correct! Bottle isn't empty.`); -else console.warn(`Not quite right! Bottle should not be empty but it is already.`); +else + console.warn( + `Not quite right! Bottle should not be empty but it is already.` + ); // ACTIONS bottle.pour(); // CHECKS -if (bottle.volume === 100) console.log(`That's correct. Bottle is already full water volume cannot go beyond.`); -else console.warn(`Whoops!!! Looks like you've changed your bottle to a bigger one, it went beyond its maximum capacity up to ${bottle.volume} unit.`); +if (bottle.volume === 100) + console.log( + `That's correct. Bottle is already full water volume cannot go beyond.` + ); +else + console.warn( + `Whoops!!! Looks like you've changed your bottle to a bigger one, it went beyond its maximum capacity up to ${bottle.volume} unit.` + ); if (bottle.isFull()) console.log(`That's correct! Bottle is still full.`); else console.warn(`Not quite right! Bottle should be still full but is not.`); @@ -85,8 +110,12 @@ bottle.drink(); bottle.drink(); // CHECKS -if (bottle.volume === 70) console.log(`That's correct! Water volume is ${bottle.volume}.`); -else console.warn(`Not quite right! Water volume should be 70 unit instead of ${bottle.volume}.`); +if (bottle.volume === 70) + console.log(`That's correct! Water volume is ${bottle.volume}.`); +else + console.warn( + `Not quite right! Water volume should be 70 unit instead of ${bottle.volume}.` + ); // ACTIONS bottle.drink(); @@ -98,7 +127,10 @@ if (!bottle.isFull()) console.log(`That's correct! Bottle isn't full.`); else console.warn(`Not quite right! Bottle should not be full but it is.`); if (!bottle.isEmpty()) console.log(`That's correct! Bottle isn't empty yet.`); -else console.warn(`Not quite right! Bottle should not be still empty but it is already.`); +else + console.warn( + `Not quite right! Bottle should not be still empty but it is already.` + ); // ACTIONS bottle.drink(); @@ -108,17 +140,28 @@ bottle.drink(); // CHECKS if (bottle.isEmpty()) console.log(`That's correct! Bottle is finally emptied.`); -else console.warn(`Not quite right. Bottle should be already empty but it is not.`); - -if (bottle.volume === 0) console.log(`That's correct! Empty bottle volume is repesented as zero.`); -else console.warn(`Not quite right. Volume should be zero instead of ${bottle.volume}.`); +else + console.warn( + `Not quite right. Bottle should be already empty but it is not.` + ); + +if (bottle.volume === 0) + console.log(`That's correct! Empty bottle volume is repesented as zero.`); +else + console.warn( + `Not quite right. Volume should be zero instead of ${bottle.volume}.` + ); // ACTIONS bottle.drink(); // CHECKS -if (bottle.volume === 0) console.log(`That's correct! Water volume cannot go below zero.`); -else console.warn(`Whoops!!! Looks like your water volume went negative. Your water volume is ${bottle.volume} unit.`); +if (bottle.volume === 0) + console.log(`That's correct! Water volume cannot go below zero.`); +else + console.warn( + `Whoops!!! Looks like your water volume went negative. Your water volume is ${bottle.volume} unit.` + ); if (bottle.isEmpty()) console.log(`That's correct! Bottle is still empty.`); else console.warn(`Not quite right. Bottle should be empty but it is not.`); @@ -127,18 +170,28 @@ else console.warn(`Not quite right. Bottle should be empty but it is not.`); bottle.pour(); // CHECKS -if (bottle.volume === 10) console.log(`That's correct! Water volume is ${bottle.volume}.`); -else console.warn(`Not quite right! Water volume should be 10 unit instead of ${bottle.volume}.`); +if (bottle.volume === 10) + console.log(`That's correct! Water volume is ${bottle.volume}.`); +else + console.warn( + `Not quite right! Water volume should be 10 unit instead of ${bottle.volume}.` + ); if (!bottle.isFull()) console.log(`That's correct! Bottle isn't yet full.`); else console.warn(`Not quite right! Bottle should not be full but it is.`); -if (!bottle.isEmpty()) console.log(`That's correct! Bottle isn't empty anymore.`); -else console.warn(`Not quite right! Bottle should not be empty again but it is still.`); +if (!bottle.isEmpty()) + console.log(`That's correct! Bottle isn't empty anymore.`); +else + console.warn( + `Not quite right! Bottle should not be empty again but it is still.` + ); // ACTIONS bottle.drink(); // CHECKS -if (bottle.isEmpty()) console.log(`That's correct! Bottle is emptied once more.`); -else console.warn(`Not quite right. Bottle should be empty again but it is not.`); +if (bottle.isEmpty()) + console.log(`That's correct! Bottle is emptied once more.`); +else + console.warn(`Not quite right. Bottle should be empty again but it is not.`); diff --git a/week-4/Homework/mandatory/4-groceries.js b/week-4/Homework/mandatory/4-groceries.js index c70b3a0c7..e18175cd7 100644 --- a/week-4/Homework/mandatory/4-groceries.js +++ b/week-4/Homework/mandatory/4-groceries.js @@ -11,7 +11,7 @@ that contains the missing ingredients to your menus. It is stored in the "weekly Complete the exercises below. */ -// Here is your +// Here is your let weeklyMealPlan = { monday: ["Cheese", "Eggs", "Tomato", "Paprika", "Leek"], tuesday: ["Wrap", "Tuna", "Canned beans", "Cheese", "Carrot", "Aubergine"], @@ -19,7 +19,7 @@ let weeklyMealPlan = { thursday: ["Lamb", "Salt", "Bulgur", "Potato"], fridray: ["Rice milk", "Blueberries", "Porridge", "Banana", "Cinnamon"], saturday: ["Olive oil", "Potato", "Salmon", "Asparagus"], - sunday: [] + sunday: [], }; /* @@ -29,8 +29,8 @@ Exercise 1: */ // Gather all week item names into this array let weeklyGroceriesToBuy = []; - - +weeklyGroceriesToBuy = Object.values(weeklyMealPlan); +console.log(weeklyGroceriesToBuy); /* Exercise 2: @@ -39,9 +39,11 @@ Exercise 2: */ // Gather weekend item names into this array let weekendGroceriesToBuy = []; - - - +weekendGroceriesToBuy = Object.values( + weeklyMealPlan.saturday, + weeklyMealPlan.sunday +); +console.log(weekendGroceriesToBuy); /* Exercise 2: Loop through your weekly meal plan: @@ -50,13 +52,19 @@ Exercise 2: Finally use console.log() to print out the Object. */ -// Gather weekend item names into this array -let numberOfItemsPerWeak = { - monday: 0, - tuesday: 0, - wednesday: 0, - thursday: 0, - fridray: 0, - saturday: 0, - sunday: 0 -}; +//Gather weekend item names into this array +let numberOfItemsPerWeak = []; +for (let day in weeklyMealPlan) { + numberOfItemsPerWeak.push(`${day}: ${weeklyMealPlan[day].length}`); +} +console.log(numberOfItemsPerWeak); + +// let numberOfItemsPerWeak = { +// monday: 0, +// tuesday: 0, +// wednesday: 0, +// thursday: 0, +// fridray: 0, +// saturday: 0, +// sunday: 0, +// }; diff --git a/week-4/InClass/A-objects-intro/exercise-part-0.js b/week-4/InClass/A-objects-intro/exercise-part-0.js index 58d6d28e7..8cfc8b2f3 100644 --- a/week-4/InClass/A-objects-intro/exercise-part-0.js +++ b/week-4/InClass/A-objects-intro/exercise-part-0.js @@ -4,4 +4,13 @@ Describe your own laptop as a JavaScript object Try to think of as many properties as you can! -*/ \ No newline at end of file +*/ +let laptop = { + Brand: "Dell", + Os: "Linux", + screenSize: 14, + cpu: "Core I 5", + Hdd: 256, + color: "Black", +}; +console.log(laptop); diff --git a/week-4/InClass/A-objects-intro/exercise-part-1.js b/week-4/InClass/A-objects-intro/exercise-part-1.js index 44cdf0ee0..775bf62f7 100644 --- a/week-4/InClass/A-objects-intro/exercise-part-1.js +++ b/week-4/InClass/A-objects-intro/exercise-part-1.js @@ -7,3 +7,36 @@ Assign each of them to a separate variable */ +let mobilePhone = { + Brand: "Iphone", + screenSize: "5.8", + Model: "7 plus", + capacity: "128 GB", +}; +let tv = { + Brand: "Samsung", + screenSize: "55 inches", + color: "Silver", + smart: true, + preInstaldedApps: true, +}; +let sofa = { + Brand: "DFS", + "How Many Seaters": 7, + color: "Teal", + material: "Fabric", +}; +let house = { + "Number of Bedrooms": 2, + Flat: true, + house: false, + level: 2, + furnished: true, +}; +let fridge = { + Brand: "Hot Point", + color: "Black", + capacity: "230 Liter", + "Fridge Freezer": true, +}; +console.log(fridge); diff --git a/week-4/InClass/A-objects-intro/exercise-part-2.js b/week-4/InClass/A-objects-intro/exercise-part-2.js index 356828587..23a9f5a0b 100644 --- a/week-4/InClass/A-objects-intro/exercise-part-2.js +++ b/week-4/InClass/A-objects-intro/exercise-part-2.js @@ -5,17 +5,18 @@ The objects below have some syntax issues - try and fix them all! */ let kitten = { - fur colour: "orange", - age "23" + "fur colour": "orange", + age: 23, }; -let laptop = - brand: "Lenovo" - ram "5GB" -} +let laptop = { + brand: "Lenovo", + ram: "5 GB", +}; let phone = { - operating system "iOS", - hasStylus: true, - megapixels 12 - "batteryLife": "24 hours" \ No newline at end of file + "operating system": "iOS", + "has Stylus": true, + "mega pixels": 12, + "battery Life": "24 hours", +}; diff --git a/week-4/InClass/B-objects-get-set/exercise-1.js b/week-4/InClass/B-objects-get-set/exercise-1.js index 4fd71e60b..9bb642ceb 100644 --- a/week-4/InClass/B-objects-get-set/exercise-1.js +++ b/week-4/InClass/B-objects-get-set/exercise-1.js @@ -3,16 +3,15 @@ */ let kitten = { - ageMonths: 3, - isFemale: true, - furColour: "brown" + ageMonths: 3, + isFemale: true, + furColour: "brown", }; // YOUR CODE GOES BELOW HERE +console.log(kitten.ageMonths); +console.log(kitten.isFemale); +console.log(kitten.furColour); - - - - -// YOUR CODE GOES ABOVE HERE \ No newline at end of file +// YOUR CODE GOES ABOVE HERE diff --git a/week-4/InClass/B-objects-get-set/exercise-2.js b/week-4/InClass/B-objects-get-set/exercise-2.js index efdb092b1..588805729 100644 --- a/week-4/InClass/B-objects-get-set/exercise-2.js +++ b/week-4/InClass/B-objects-get-set/exercise-2.js @@ -5,14 +5,14 @@ */ let phone = { - brand: 'iPhone, - model 'iPhone X' - launchYear: 2017, - is Unlocked: true -; + brand: "iPhone", + model: "iPhone X", + launchYear: 2017, + isUnlocked: true, +}; -let phoneBrand = phone.bbrand; -let phoneLaunchYear = phone[launchYear]; +let phoneBrand = phone.brand; +let phoneLaunchYear = phone["launchYear"]; // DO NOT MODIFY BELOW THIS LINE @@ -21,4 +21,4 @@ console.log(phoneLaunchYear); // it should output: // iPhone -// 2017 \ No newline at end of file +// 2017 diff --git a/week-4/InClass/B-objects-get-set/exercise-3.js b/week-4/InClass/B-objects-get-set/exercise-3.js index 1f057083b..541c8c6f3 100644 --- a/week-4/InClass/B-objects-get-set/exercise-3.js +++ b/week-4/InClass/B-objects-get-set/exercise-3.js @@ -3,9 +3,11 @@ */ // WRITE CODE BELOW THIS - +let kitten = { + name: "Gilbert", +}; // WRITE CODE ABOVE THIS console.log(kitten.name); -// -> it should output: "Gilbert" \ No newline at end of file +// -> it should output: "Gilbert" diff --git a/week-4/InClass/B-objects-get-set/exercise-4.js b/week-4/InClass/B-objects-get-set/exercise-4.js index 4947cb50f..fac3fcce0 100644 --- a/week-4/InClass/B-objects-get-set/exercise-4.js +++ b/week-4/InClass/B-objects-get-set/exercise-4.js @@ -3,21 +3,21 @@ */ let dog = { - name: 'Billy', - wantsToPlay: false + name: "Billy", + wantsToPlay: false, }; // WRITE CODE BELOW THIS LINE - +dog.name = "Rex"; +dog.wantsToPlay = true; // WRITE CODE ABOVE THIS LINE - //DO NOT MODIFY BELOW console.log(dog.name); console.log(dog.wantsToPlay); // it should output: // Rex -// true \ No newline at end of file +// true diff --git a/week-4/InClass/C-more-complex-objects/exercise-1.js b/week-4/InClass/C-more-complex-objects/exercise-1.js index ae8fea487..fcf891992 100644 --- a/week-4/InClass/C-more-complex-objects/exercise-1.js +++ b/week-4/InClass/C-more-complex-objects/exercise-1.js @@ -5,12 +5,12 @@ */ let house = { - address: "1 Kinning Park", - previousOwners: ["Claire M.", "John A."], - currentOwner: { - firstName: "Margaret", - lastName: "Conway" - } + address: "1 Kinning Park", + previousOwners: ["Claire M.", "John A."], + currentOwner: { + firstName: "Margaret", + lastName: "Conway", + }, }; /* @@ -20,14 +20,23 @@ let house = { */ // - change the address of "house" to '51 Berkley Road' +house.address = "51 Berkley Road"; // - change the previous owners of "house" to ["Brian M.", "Fiona S."] +house.previousOwners = ["Brian M.", "Fiona S."]; // - change the last name of the current owner of "house" to "Montgomery" - +house.currentOwner.lastName = "Montgomery"; /* DO NOT EDIT ANYTHING BELOW THIS LINE */ -console.log("Expected result: 51 Berkley Road. Actual result: " + house.address); -console.log("Expected result: Brian M., Fiona S. Actual result: " + house.previousOwners.toString()); -console.log("Expected result: Montgomery. Actual result: " + house.currentOwner.lastName); \ No newline at end of file +console.log( + "Expected result: 51 Berkley Road. Actual result: " + house.address +); +console.log( + "Expected result: Brian M., Fiona S. Actual result: " + + house.previousOwners.toString() +); +console.log( + "Expected result: Montgomery. Actual result: " + house.currentOwner.lastName +); diff --git a/week-4/InClass/C-more-complex-objects/exercise-2.js b/week-4/InClass/C-more-complex-objects/exercise-2.js index 69b3768aa..3677b6b98 100644 --- a/week-4/InClass/C-more-complex-objects/exercise-2.js +++ b/week-4/InClass/C-more-complex-objects/exercise-2.js @@ -6,17 +6,17 @@ */ let house = { - address: "1 Kinning Park", - previousOwners: ["Claire M.", "John A."], - currentOwner: { - firstName: "Margaret", - lastName: "Conway" - } + address: "1 Kinning Park", + previousOwners: ["Claire M.", "John A."], + currentOwner: { + firstName: "Margaret", + lastName: "Conway", + }, }; let newCurrentOwner = { - firstName: "Georgina", - lastName: "Hernandez" + firstName: "Georgina", + lastName: "Hernandez", }; /* @@ -26,17 +26,22 @@ let newCurrentOwner = { */ // - assign the value of the variable 'newCurrentOwner' as the value to the house's "currentOwner" +house.currentOwner = newCurrentOwner; // - from the list of previous owners, replace only "John A." with "Stephen B." +house.previousOwners[1] = "Stephen B."; // - give the house a new property called 'isForSale' with the value 'false' - - - +house.isForSale = false; /* DO NOT EDIT ANYTHING BELOW THIS LINE */ console.log( - "Did you correctly assign the new owner using the given variable?", - `Expected result: true. Actual result: ${(house.currentOwner === newCurrentOwner)}`); -console.log(`Expected result: Claire M., Stephen B.Actual result: ${house.previousOwners.toString()}`); -console.log(`Expected result: false.Actual result: ${house.isForSale}`); \ No newline at end of file + "Did you correctly assign the new owner using the given variable?", + `Expected result: true. Actual result: ${ + house.currentOwner === newCurrentOwner + }` +); +console.log( + `Expected result: Claire M., Stephen B.Actual result: ${house.previousOwners.toString()}` +); +console.log(`Expected result: false.Actual result: ${house.isForSale}`); diff --git a/week-4/InClass/C-more-complex-objects/exercise-3.js b/week-4/InClass/C-more-complex-objects/exercise-3.js index f461e7d64..fd7fdccae 100644 --- a/week-4/InClass/C-more-complex-objects/exercise-3.js +++ b/week-4/InClass/C-more-complex-objects/exercise-3.js @@ -5,23 +5,23 @@ */ let kinningParkHouse = { - address: "1 Kinning Park", - price: 180000, - currentOwner: { - firstName: "Margaret", - lastName: "Conway", - email: "margaret@fake-emails.com" - } + address: "1 Kinning Park", + price: 180000, + currentOwner: { + firstName: "Margaret", + lastName: "Conway", + email: "margaret@fake-emails.com", + }, }; let parkAvenueHouse = { - address: "50 Park Avenue", - price: 195000, - currentOwner: { - firstName: "Marie", - lastName: "McDonald", - email: "marie.m@real-emails.com" - } + address: "50 Park Avenue", + price: 195000, + currentOwner: { + firstName: "Marie", + lastName: "McDonald", + email: "marie.m@real-emails.com", + }, }; /* @@ -32,23 +32,39 @@ let parkAvenueHouse = { // returns the full name (first name + last name) of the owner of the house function getOwnerFullName(house) { - + return `${kinningParkHouse.currentOwner.firstName} ${kinningParkHouse.currentOwner.lastName}`; } - // returns an array of the owners' email addresses of the two houses function getEmailAddresses(house1, house2) { - + return `${kinningParkHouse.currentOwner.email} , ${parkAvenueHouse.currentOwner.email}`; } // returns the address for the cheapest house out of the two function getCheapestAddress(house1, house2) { - + if (kinningParkHouse.price < parkAvenueHouse.price) { + return kinningParkHouse.address; + } else { + return parkAvenueHouse.address; + } } - /* DO NOT EDIT ANYTHING BELOW THIS LINE */ -console.log(`Expected result: Margaret Conway. Actual result: ${getOwnerFullName(kinningParkHouse)}`); -console.log(`Expected result: margaret@fake-emails.com, marie.m@real-emails.com. Actual result: ${getEmailAddresses(kinningParkHouse, parkAvenueHouse)}`); -console.log(`Expected result: 1 Kinning Park. Actual result: ${getCheapestAddress(parkAvenueHouse, kinningParkHouse)}`); \ No newline at end of file +console.log( + `Expected result: Margaret Conway. Actual result: ${getOwnerFullName( + kinningParkHouse + )}` +); +console.log( + `Expected result: margaret@fake-emails.com, marie.m@real-emails.com. Actual result: ${getEmailAddresses( + kinningParkHouse, + parkAvenueHouse + )}` +); +console.log( + `Expected result: 1 Kinning Park. Actual result: ${getCheapestAddress( + parkAvenueHouse, + kinningParkHouse + )}` +); diff --git a/week-4/InClass/D-methods/exercise-1.js b/week-4/InClass/D-methods/exercise-1.js index 8de0f8c30..30a7521a9 100644 --- a/week-4/InClass/D-methods/exercise-1.js +++ b/week-4/InClass/D-methods/exercise-1.js @@ -3,16 +3,18 @@ A person named Alice is defined below. Add a method "greet" so this person can say hello. */ - let person = { - name: "Alice", - age: 25 + name: "Alice", + age: 25, }; - - +function greet() { + return "say hello"; +} +person.greet = greet; /* DO NOT EDIT ANYTHING BELOW THIS LINE */ - -console.log(`Expected result: Hello everybody. Actual result: ${person.greet()}`); \ No newline at end of file +console.log( + `Expected result: Hello everybody. Actual result: ${person.greet()}` +); diff --git a/week-4/InClass/D-methods/exercise-2.js b/week-4/InClass/D-methods/exercise-2.js index 8e993fc69..f5141e5bb 100644 --- a/week-4/InClass/D-methods/exercise-2.js +++ b/week-4/InClass/D-methods/exercise-2.js @@ -4,15 +4,18 @@ Add a method "sayName" so this person can say their own name. Hint: use 'this' keyword to access the name property. */ - let person = { - name: "Alice", - age: 25 + name: "Alice", + age: 25, }; - - +function sayName() { + return `My name is ${this.name}`; +} +person.sayName = sayName; /* DO NOT EDIT ANYTHING BELOW THIS LINE */ -console.log(`Expected result: 'My name is Alice'. Actual result: ${person.sayName()}`); \ No newline at end of file +console.log( + `Expected result: 'My name is Alice'. Actual result: ${person.sayName()}` +); diff --git a/week-4/InClass/D-methods/exercise-3.js b/week-4/InClass/D-methods/exercise-3.js index be237483b..7aa196127 100644 --- a/week-4/InClass/D-methods/exercise-3.js +++ b/week-4/InClass/D-methods/exercise-3.js @@ -3,26 +3,26 @@ The following code contains syntax errors - try and fix them! Once you fix them, run this file, it should output the correct values! */ - let person = { - name: "Alice", - age: 25, - currentAddress: "Glasgow", - changeAddress: (newAddress) { - currentAddress = newAddress; - }, - celebrateBirthday: function { - that.age = that.age + 1; - } + name: "Alice", + age: 25, + currentAddress: "Glasgow", + changeAddress: function (newAddress) { + return (this.currentAddress = newAddress); + }, + celebrateBirthday: function () { + this.age = this.age + 1; + }, }; - /* DO NOT EDIT ANYTHING BELOW THIS LINE */ person.changeAddress("Edinburgh"); -console.log(`Expected result: Edinburgh. Actual result: ${person.currentAddress}`); +console.log( + `Expected result: Edinburgh. Actual result: ${person.currentAddress}` +); person.celebrateBirthday(); console.log(`Expected result: 26. Actual result: ${person.age}`); diff --git a/week-4/InClass/D-methods/exercise-4.js b/week-4/InClass/D-methods/exercise-4.js index d89214a72..77b9335a9 100644 --- a/week-4/InClass/D-methods/exercise-4.js +++ b/week-4/InClass/D-methods/exercise-4.js @@ -3,17 +3,21 @@ Alice has a list of good friends. Define a method "makeFriend" to add a new friend to her list. */ - let person = { - name: "Alice", - friends: ["John", "Nina"] + name: "Alice", + friends: ["John", "Nina"], }; - +function makeFriend(newFriend) { + return this.friends.push(newFriend); +} +person.makeFriend = makeFriend; /* DO NOT EDIT ANYTHING BELOW THIS LINE */ person.makeFriend("Bob"); -console.log(`Expected result: 'John,Nina,Bob'. Actual result: ${person.friends}`); \ No newline at end of file +console.log( + `Expected result: 'John,Nina,Bob'. Actual result: ${person.friends}` +); diff --git a/week-4/InClass/D-methods/exercise-5.js b/week-4/InClass/D-methods/exercise-5.js index dcd198c47..70950cb86 100644 --- a/week-4/InClass/D-methods/exercise-5.js +++ b/week-4/InClass/D-methods/exercise-5.js @@ -1,6 +1,6 @@ /* A coffee machine is defined below. -One can buy three different coffees. +One person can buy three different coffees. Complete the methods "insertMoney" and "getCoffee" to match the expected result. insertMoney takes an amount in parameter to add money in the coffee machine. @@ -9,35 +9,53 @@ only if the inserted amount is greater or equal than the price of the coffee! */ let coffeeMachine = { - brand: "Super Coffee", - prices: { - cappuccino: 2.40, - blackCoffee: 1.50, - flatWhite: 3.00 - }, - insertedAmount: 0, - insertMoney: function (amount) { - - }, - getCoffee: function (coffee) { - + brand: "Super Coffee", + prices: { + cappuccino: 2.4, + blackCoffee: 1.5, + flatWhite: 3.0, + }, + insertedAmount: 0, + insertMoney: function (amount) { + this.insertedAmount = amount; + }, + getCoffee: function (coffee) { + if (this.insertedAmount >= coffeeMachine.prices[coffee]) { + return `Please take your ${coffee}`; + } else { + return `Sorry you don't have enough money for a ${coffee}`; } + }, }; - /* DO NOT EDIT ANYTHING BELOW THIS LINE */ -coffeeMachine.insertMoney(2.40); -console.log(`Expected result: 'Please take your cappuccino'. Actual result: ${coffeeMachine.getCoffee('cappuccino')}`); - -coffeeMachine.insertMoney(1.50); -console.log(`Expected result: 'Please take your blackCoffee'. Actual result: ${coffeeMachine.getCoffee('blackCoffee')}`); - -coffeeMachine.insertMoney(4.00); -console.log(`Expected result: 'Please take your flatWhite'. Actual result: ${coffeeMachine.getCoffee('flatWhite')}`); - -coffeeMachine.insertMoney(2.40); -console.log(`Expected result: 'Sorry you don't have enough money for a flatWhite'. Actual result: ${coffeeMachine.getCoffee('flatWhite')}`); - +coffeeMachine.insertMoney(2.4); +console.log( + `Expected result: 'Please take your cappuccino'. Actual result: ${coffeeMachine.getCoffee( + "cappuccino" + )}` +); + +coffeeMachine.insertMoney(1.5); +console.log( + `Expected result: 'Please take your blackCoffee'. Actual result: ${coffeeMachine.getCoffee( + "blackCoffee" + )}` +); + +coffeeMachine.insertMoney(4.0); +console.log( + `Expected result: 'Please take your flatWhite'. Actual result: ${coffeeMachine.getCoffee( + "flatWhite" + )}` +); + +coffeeMachine.insertMoney(2.4); +console.log( + `Expected result: 'Sorry you don't have enough money for a flatWhite'. Actual result: ${coffeeMachine.getCoffee( + "flatWhite" + )}` +); diff --git a/week-4/InClass/E-arrays-of-objects/exercise-1.js b/week-4/InClass/E-arrays-of-objects/exercise-1.js index 8d39a8154..7ce7e4985 100644 --- a/week-4/InClass/E-arrays-of-objects/exercise-1.js +++ b/week-4/InClass/E-arrays-of-objects/exercise-1.js @@ -5,18 +5,18 @@ */ var person1 = { - name: "Alice", - age: 25 + name: "Alice", + age: 25, }; var person2 = { - name: "Bob", - age: 30 + name: "Bob", + age: 30, }; var person3 = { - name: "John", - age: 20 + name: "John", + age: 20, }; /* @@ -24,23 +24,37 @@ DO NOT EDIT ANYTHING ABOVE THIS LINE WRITE YOUR CODE BELOW */ +var persons = [person1, person2, person3]; // Complete here -var persons = // Complete here - -var personNames = // Complete here - -var personsYoungerThan28YearsOld = // Complete here - +var personNames = persons.map((names) => names.name); // Complete here +var personsYoungerThan28YearsOld = persons.filter( + (personsYoungerThan28YearsOld) => personsYoungerThan28YearsOld.age < 28 +); // Complete here /* DO NOT EDIT ANYTHING BELOW THIS LINE */ -console.log("Question 1: array defined with 3 persons -> ", - (persons[0] === person1 && persons[1] === person2 && persons[2] === person3) ? 'Passed :)' : 'Not yet :('); - -console.log("Question 2: array containing the person names -> ", - (personNames[0] === "Alice" && personNames[1] === "Bob" && personNames[2] === "John") ? 'Passed :)' : 'Not yet :('); - -console.log("Question 3: array containing the persons younger than 28 years old -> ", - (personsYoungerThan28YearsOld[0] === person1 && personsYoungerThan28YearsOld[1] === person3) ? 'Passed :)' : 'Not yet :('); +console.log( + "Question 1: array defined with 3 persons -> ", + persons[0] === person1 && persons[1] === person2 && persons[2] === person3 + ? "Passed :)" + : "Not yet :(" +); + +console.log( + "Question 2: array containing the person names -> ", + personNames[0] === "Alice" && + personNames[1] === "Bob" && + personNames[2] === "John" + ? "Passed :)" + : "Not yet :(" +); + +console.log( + "Question 3: array containing the persons younger than 28 years old -> ", + personsYoungerThan28YearsOld[0] === person1 && + personsYoungerThan28YearsOld[1] === person3 + ? "Passed :)" + : "Not yet :(" +); diff --git a/week-4/InClass/E-arrays-of-objects/exercise-2.js b/week-4/InClass/E-arrays-of-objects/exercise-2.js index 59c5c2ff8..b0b869711 100644 --- a/week-4/InClass/E-arrays-of-objects/exercise-2.js +++ b/week-4/InClass/E-arrays-of-objects/exercise-2.js @@ -7,50 +7,63 @@ Each destination has a name, a distance from Glasgow, and a list of transportati 3) Print in the console all the destination names more than 300 kms far away and reachable by train. */ - let destination1 = { - destinationName: "Edinburgh", - distanceKms: 80, - transportations: ["car", "bus", "train"] + destinationName: "Edinburgh", + distanceKms: 80, + transportations: ["car", "bus", "train"], }; let destination2 = { - destinationName: "London", - distanceKms: 650, - transportations: ["car", "bus", "train"] + destinationName: "London", + distanceKms: 650, + transportations: ["car", "bus", "train"], }; let destination3 = { - destinationName: "Paris", - distanceKms: 900, - transportations: ["train", "plane"] + destinationName: "Paris", + distanceKms: 900, + transportations: ["train", "plane"], }; let destination4 = { - destinationName: "Dublin", - distanceKms: 350, - transportations: ["plane", "ferry"] + destinationName: "Dublin", + distanceKms: 350, + transportations: ["plane", "ferry"], }; -let travelDestinations = [destination1, destination2, destination3, destination4]; +let travelDestinations = [ + destination1, + destination2, + destination3, + destination4, +]; /* DO NOT EDIT ANYTHING ABOVE THIS LINE WRITE YOUR CODE BELOW */ +let destinationNamesWithin500Kms = travelDestinations + .filter((destination) => destination.distanceKms < 500) + .map((a) => a.destinationName); // Complete here -let destinationNamesWithin500Kms = // Complete here - -let destinationNameReachableByFerry = // Complete here - -let destinationNamesMoreThan300KmsAwayByTrain = // Complete here (PRINT THE RESULT IN THE CONSOLE USING FOREACH) - +let destinationNameReachableByFerry = travelDestinations + .filter((destination) => destination.transportations.includes("ferry")) + .map((a) => a.destinationName); // Complete here +let destinationNamesMoreThan300KmsAwayByTrain = travelDestinations + .filter((a) => a.distanceKms > 300 && a.transportations.includes("train")) + .map((b) => b.destinationName); // Complete here (PRINT THE RESULT IN THE CONSOLE USING FOREACH) /* DO NOT EDIT ANYTHING BELOW THIS LINE */ -console.log(`Question 1) Expected result: Edinburgh,Dublin, actual result: ${destinationNamesWithin500Kms}`); -console.log(`Question 2) Expected result: Dublin, actual result: ${destinationNameReachableByFerry}`); -console.log(`Question 3) Expected result: London,Paris, actual result: ${destinationNamesMoreThan300KmsAwayByTrain}`); +console.log( + `Question 1) Expected result: Edinburgh,Dublin, actual result: ${destinationNamesWithin500Kms}` +); +console.log( + `Question 2) Expected result: Dublin, actual result: ${destinationNameReachableByFerry}` +); +console.log( + `Question 3) Expected result: London,Paris, actual result: ${destinationNamesMoreThan300KmsAwayByTrain}` +); diff --git a/week-4/InClass/E-arrays-of-objects/exercise-3.js b/week-4/InClass/E-arrays-of-objects/exercise-3.js index a1ec6916f..9564e0a87 100644 --- a/week-4/InClass/E-arrays-of-objects/exercise-3.js +++ b/week-4/InClass/E-arrays-of-objects/exercise-3.js @@ -15,36 +15,36 @@ and returns the number of restaurants in this area. */ let restaurant1 = { - name: "Paesano", - totalSeats: 10, - numberOfCustomers: 8, - address: { - city: "Glasgow", - area: "center" - }, - menu: ["pizza", "calzone", "salad"] + name: "Paesano", + totalSeats: 10, + numberOfCustomers: 8, + address: { + city: "Glasgow", + area: "center", + }, + menu: ["pizza", "calzone", "salad"], }; let restaurant2 = { - name: "Ubiquitous Chip", - totalSeats: 20, - numberOfCustomers: 10, - address: { - city: "Glasgow", - area: "west" - }, - menu: ["salad", "chocolate cake", "roast lamb"] + name: "Ubiquitous Chip", + totalSeats: 20, + numberOfCustomers: 10, + address: { + city: "Glasgow", + area: "west", + }, + menu: ["salad", "chocolate cake", "roast lamb"], }; let restaurant3 = { - name: "Monkeyz", - totalSeats: 15, - numberOfCustomers: 8, - address: { - city: "Glasgow", - area: "center" - }, - menu: ["stew", "chocolate cake", "panini"] + name: "Monkeyz", + totalSeats: 15, + numberOfCustomers: 8, + address: { + city: "Glasgow", + area: "center", + }, + menu: ["stew", "chocolate cake", "panini"], }; let restaurants = [restaurant1, restaurant2, restaurant3]; @@ -54,32 +54,48 @@ DO NOT EDIT ANYTHING ABOVE THIS LINE WRITE YOUR CODE BELOW */ - let restaurantFinderApplication = { - applicationName: "Restaurant Finder", - applicationVersion: "1.0", - restaurants: restaurants, - findAvailableRestaurants: function (numberOfPeople) { - // Complete here - }, - findRestaurantServingDish: function (dishName) { - // Complete here - }, - countNumberOfRestaurantsInArea: function (area) { - // Complete here - } + applicationName: "Restaurant Finder", + applicationVersion: "1.0", + restaurants: restaurants, + findAvailableRestaurants: function (numberOfPeople) { + let findResturant = restaurants + .filter((b) => b.totalSeats - b.numberOfCustomers >= numberOfPeople) + .map((a) => a.name); // Complete here + return findResturant; + }, + findRestaurantServingDish: function (dishName) { + return restaurants + .filter((a) => a.menu.includes(dishName)) + .map((b) => b.name); + // Complete here + }, + countNumberOfRestaurantsInArea: function (area) { + return restaurants.filter((a) => a.address.area.includes(area)).length; // Complete here + }, }; - /* DO NOT EDIT ANYTHING BELOW THIS LINE */ -let restaurantsAvailableFor5People = restaurantFinderApplication.findAvailableRestaurants(5); -console.log(`Find available restaurants for 5 people: Expected result: Ubiquitous Chip,Monkeyz, actual result: ${restaurantsAvailableFor5People}`); - -let restaurantsServingSalad = restaurantFinderApplication.findRestaurantServingDish("salad"); -console.log(`Find restaurants serving salad: Expected result: Paesano,Ubiquitous Chip, actual result: ${restaurantsServingSalad}`); - -let numberOfRestaurantsInCityCentre = restaurantFinderApplication.countNumberOfRestaurantsInArea("center"); -console.log(`Number of restaurants in city centre: Expected result: 2, actual result: ${numberOfRestaurantsInCityCentre}`); +let restaurantsAvailableFor5People = restaurantFinderApplication.findAvailableRestaurants( + 5 +); +console.log( + `Find available restaurants for 5 people: Expected result: Ubiquitous Chip,Monkeyz, actual result: ${restaurantsAvailableFor5People}` +); + +let restaurantsServingSalad = restaurantFinderApplication.findRestaurantServingDish( + "salad" +); +console.log( + `Find restaurants serving salad: Expected result: Paesano,Ubiquitous Chip, actual result: ${restaurantsServingSalad}` +); + +let numberOfRestaurantsInCityCentre = restaurantFinderApplication.countNumberOfRestaurantsInArea( + "center" +); +console.log( + `Number of restaurants in city centre: Expected result: 2, actual result: ${numberOfRestaurantsInCityCentre}` +); diff --git a/week-4/InClass/F-object-keys/exercise-part-0.js b/week-4/InClass/F-object-keys/exercise-part-0.js index d9b10855b..e38b55d32 100644 --- a/week-4/InClass/F-object-keys/exercise-part-0.js +++ b/week-4/InClass/F-object-keys/exercise-part-0.js @@ -5,28 +5,28 @@ Return the keys of the following object */ let capitalCities = { - scotland: 'Edinburgh', - kenya: 'Nairobi', - australia: 'Canberra', - canada: 'Ottawa' + scotland: "Edinburgh", + kenya: "Nairobi", + australia: "Canberra", + canada: "Ottawa", }; let highScores = { - 55: 'Alistair', - 100: 'David', - 89: 'Hannah', - 34: ['Sergi', 'Frank',] + 55: "Alistair", + 100: "David", + 89: "Hannah", + 34: ["Sergi", "Frank"], }; // ONLY EDIT BELOW HERE -let capitalCitiesKeys = ; -let highScoresKeys; +let capitalCitiesKeys = Object.keys(capitalCities); +let highScoresKeys = Object.keys(highScores); // ONLY EDIT ABOVE HERE console.log(capitalCitiesKeys); // prints [ 'scotland', 'kenya', 'australia', 'canada' ] -console.log(highScoresKeys) +console.log(highScoresKeys); // prints ['34, '55', '89', '100'] diff --git a/week-4/InClass/F-object-keys/exercise-part-1.js b/week-4/InClass/F-object-keys/exercise-part-1.js index b8d4be714..7b58171cd 100644 --- a/week-4/InClass/F-object-keys/exercise-part-1.js +++ b/week-4/InClass/F-object-keys/exercise-part-1.js @@ -10,14 +10,14 @@ let mentorsAges = { james: 29, JOSH: 35, JAMIE: 25, - Mozafar: 30 + Mozafar: 30, }; // ONLY EDIT BELOW THIS LINE -let mentorsNames = ; +let mentorsNames = Object.keys(mentorsAges); -let mentorsNamedUppercased = ; +let mentorsNamedUppercased = mentorsNames.map((a) => a.toUpperCase()); // ONLY EDIT ABOVE THIS LINE diff --git a/week-4/InClass/F-object-keys/exercise-part-2.js b/week-4/InClass/F-object-keys/exercise-part-2.js index 0c1571253..23f5c919a 100644 --- a/week-4/InClass/F-object-keys/exercise-part-2.js +++ b/week-4/InClass/F-object-keys/exercise-part-2.js @@ -9,40 +9,38 @@ Use the provided console.log statements below and follow the instructions above */ let storeBranches = { - glasgow: { - manager: 'Andrew', - assistant: 'Laura', + manager: "Andrew", + assistant: "Laura", interns: { - head_intern: 'Mozafar', - intern: 'James' - } + head_intern: "Mozafar", + intern: "James", + }, }, edinburgh: { - director: 'Kelly', - manager: 'Sally', - assistant: 'Derek', + director: "Kelly", + manager: "Sally", + assistant: "Derek", interns: { - head_intern: 'John', - intern: 'Sarah' - } - } -} - + head_intern: "John", + intern: "Sarah", + }, + }, +}; // ONLY EDIT BELOW THIS LINE -// # 1 get the names of the cities +// # 1 get the names of the cities // prints [ 'glasgow', 'edinburgh' ] -console.log() +console.log(Object.keys(storeBranches)); // # 2 get the positions in Glasgow // prints [ 'manager', 'assistant', 'interns' ] -console.log() +console.log(Object.keys(storeBranches.glasgow)); // # 3 get the positions for internt in Glasgow // prints [ 'head_intern', 'intern' ] -console.log() +console.log(Object.keys(storeBranches.glasgow.interns)); // ONLY EDIT ABOVE THIS LINE diff --git a/week-4/InClass/forinLoop.js b/week-4/InClass/forinLoop.js index 1083c9e84..e065035f2 100644 --- a/week-4/InClass/forinLoop.js +++ b/week-4/InClass/forinLoop.js @@ -16,8 +16,12 @@ var UKBigCitiesInMillions = { //1- We discovered a small error in the calculations, we need to add 200 thousdands to each city under 1 million //create a loop that write the names of the city over 1 million only to the console // Example : "The city of x has a popluation of 1.5 million" -for (let city in UKBigCitiesInMillions) { -} +// for (let city in UKBigCitiesInMillions) { +// if (UKBigCitiesInMillions[city] < 1) return UKBigCitiesInMillions[city] + 0.2; +// console.log( +// `The city of ${city} has a popluation of ${UKBigCitiesInMillions[city]} million` +// ); +// } //2-We need to know in which area each city is //we looking for an output like "x is in Scotland and has population of y millions" @@ -27,4 +31,17 @@ var England = ["Manchester", "Birmingham", "London", "Newcastle"]; var Wales = ["Cardiff", "Swansea"]; for (let city in UKBigCitiesInMillions) { + if (Scotland.includes(city)) { + console.log( + `${city} is in Scotland and has population of ${UKBigCitiesInMillions[city]} millions` + ); + } else if (England.includes(city)) { + console.log( + `${city} is in England and has population of ${UKBigCitiesInMillions[city]} millions` + ); + } else { + console.log( + `${city} is in Wales and has population of ${UKBigCitiesInMillions[city]} millions` + ); + } } From 65211b5eee59e89df0cd89ef0a87260ee06998ec Mon Sep 17 00:00:00 2001 From: Hedyeh Date: Tue, 26 May 2020 00:19:43 +0100 Subject: [PATCH 2/5] some changes --- week-4/Homework/mandatory/4-groceries.js | 26 ++++++++++++------------ 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/week-4/Homework/mandatory/4-groceries.js b/week-4/Homework/mandatory/4-groceries.js index e18175cd7..c9bdde766 100644 --- a/week-4/Homework/mandatory/4-groceries.js +++ b/week-4/Homework/mandatory/4-groceries.js @@ -53,18 +53,18 @@ Exercise 2: Finally use console.log() to print out the Object. */ //Gather weekend item names into this array -let numberOfItemsPerWeak = []; + +let numberOfItemsPerWeak = { + monday: 0, + tuesday: 0, + wednesday: 0, + thursday: 0, + fridray: 0, + saturday: 0, + sunday: 0, +}; for (let day in weeklyMealPlan) { - numberOfItemsPerWeak.push(`${day}: ${weeklyMealPlan[day].length}`); -} -console.log(numberOfItemsPerWeak); + let numberOfItemsPerWeak = `${day}: ${weeklyMealPlan[day].length}`; -// let numberOfItemsPerWeak = { -// monday: 0, -// tuesday: 0, -// wednesday: 0, -// thursday: 0, -// fridray: 0, -// saturday: 0, -// sunday: 0, -// }; + console.log(numberOfItemsPerWeak); +} From 697625062b89d746ce7d9859f28a292b20f44751 Mon Sep 17 00:00:00 2001 From: Hedyeh Date: Tue, 26 May 2020 20:04:24 +0100 Subject: [PATCH 3/5] update excersise 4 --- week-4/Homework/mandatory/4-groceries.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/week-4/Homework/mandatory/4-groceries.js b/week-4/Homework/mandatory/4-groceries.js index c9bdde766..63347092e 100644 --- a/week-4/Homework/mandatory/4-groceries.js +++ b/week-4/Homework/mandatory/4-groceries.js @@ -64,7 +64,6 @@ let numberOfItemsPerWeak = { sunday: 0, }; for (let day in weeklyMealPlan) { - let numberOfItemsPerWeak = `${day}: ${weeklyMealPlan[day].length}`; - - console.log(numberOfItemsPerWeak); + numberOfItemsPerWeak[day] = weeklyMealPlan[day].length; } +console.log(numberOfItemsPerWeak); From a2fd0b478bccad22cedace5dbbfe8cf6b128fbf6 Mon Sep 17 00:00:00 2001 From: Hedyeh Date: Tue, 9 Jun 2020 02:22:46 +0100 Subject: [PATCH 4/5] week-5 3-project done --- .../mandatory/2-exercises/exercises.js | 56 ++++++++++++++++--- .../Homework/mandatory/3-project/index.html | 6 +- .../Homework/mandatory/3-project/js/main.js | 54 ++++++++++++++++++ 3 files changed, 106 insertions(+), 10 deletions(-) diff --git a/week-5/Homework/mandatory/2-exercises/exercises.js b/week-5/Homework/mandatory/2-exercises/exercises.js index cb8c0f42d..30e91a3df 100644 --- a/week-5/Homework/mandatory/2-exercises/exercises.js +++ b/week-5/Homework/mandatory/2-exercises/exercises.js @@ -37,9 +37,16 @@ *

Plumber

* */ -function insertPeopleData(arrayOfPeople) { - let content = document.querySelector("#content"); - //Write your code in here + + function insertPeopleData(arrayOfPeople) { + let content = document.querySelector("#content"); + for (let i = 0; i < arrayOfPeople.length; i++) { + var h1El = document.createElement("h1"); + h1El.textContent = arrayOfPeople[i].name; + content.appendChild(h1El); + var h2El = document.createElement("h2"); + h2El.textContent = arrayOfPeople[i].job; + content.appendChild(h2El) } /** @@ -51,8 +58,15 @@ function insertPeopleData(arrayOfPeople) { * * Hint for type of lists in HTML: https://www.w3schools.com/html/html_lists.asp */ + function insertShoppingList(shoppingList) { - //Write your code in here + let content = document.querySelector("#content"); + let listToBuy = document.createElement("ul"); + for (let i = 0; i < shoppingList.length; i++) { + let list = document.createElement("li"); + list.textContent = shoppingList[i]; + listToBuy.appendChild(list); + content.appendChild(listToBuy); } /** @@ -71,9 +85,37 @@ function insertShoppingList(shoppingList) { * * The end result should look something like this: https://hyf-js2-week1-makeme-ex1-demo.herokuapp.com */ -function insertBooks(books) { - //Write your code in here -} + + function insertBooks(books) { + let content = document.querySelector("#content"); + let unorderedList = document.createElement("ul"); + content.appendChild(unorderedList); + for (let i = 0; i < books.length; i++) { + let liOfBook = document.createElement("li"); + unorderedList.appendChild(liOfBook); + let bookList = document.createElement("p"); + bookList.textContent = books[i].title + " - " + books[i].author; + liOfBook.appendChild(bookList); + let imgEl = document.createElement("img"); + let images = [ + "https://images-na.ssl-images-amazon.com/images/I/410RTQezHYL._SX326_BO1,204,203,200_.jpg", + "https://images-na.ssl-images-amazon.com/images/I/71HMyqG6MRL.jpg", + "https://images-na.ssl-images-amazon.com/images/I/418M2053aNL.jpg", + ]; + imgEl.src = images[i]; + imgEl.width = "180"; + imgEl.height = "280"; + liOfBook.appendChild(imgEl); +}; + + if (books[i].alreadyRead === true) { + liOfBook.style.backgroundColor = "green"; + } else { + liOfBook.style.backgroundColor = "red"; + } + } + unorderedList.style.display = "flex"; + unorderedList.style.justifyContent = "space-around"; // // diff --git a/week-5/Homework/mandatory/3-project/index.html b/week-5/Homework/mandatory/3-project/index.html index 2da7cc936..fcd07b785 100644 --- a/week-5/Homework/mandatory/3-project/index.html +++ b/week-5/Homework/mandatory/3-project/index.html @@ -56,8 +56,8 @@

Bikes for Refugees

Providing donated bikes and accessories to refugees and asylum seekers in Scotland.


@@ -79,7 +79,7 @@

Register with us today:

- +

Learn more

diff --git a/week-5/Homework/mandatory/3-project/js/main.js b/week-5/Homework/mandatory/3-project/js/main.js index e69de29bb..0263265af 100644 --- a/week-5/Homework/mandatory/3-project/js/main.js +++ b/week-5/Homework/mandatory/3-project/js/main.js @@ -0,0 +1,54 @@ +var blueBtn = document.getElementById("blueBtn"); +var orangeBtn = document.getElementById("orangeBtn"); +var greenBtn = document.getElementById("greenBtn"); +var jumbotron = document.querySelector(".jumbotron"); +var donate = document.getElementById("donate"); +var volunteer = document.getElementById("Volunteer"); + +blueBtn.addEventListener("click", function () { + jumbotron.style.backgroundColor = `#588fbd`; + donate.style.backgroundColor = `#ffa500`; + volunteer.style.backgroundColor = `black`; + volunteer.style.color = `white`; +}); + +orangeBtn.addEventListener("click", function () { + jumbotron.style.backgroundColor = `#f0ad4e`; + donate.style.backgroundColor = `#5751fd`; + volunteer.style.backgroundColor = `#31b0d5`; + volunteer.style.color = `white`; +}); + +greenBtn.addEventListener("click", function () { + jumbotron.style.backgroundColor = `#87ca8a`; + donate.style.backgroundColor = `black`; + volunteer.style.backgroundColor = `#8c9c08`; +}); + +var submitBtn = document.getElementById("submitBtn"); +var emailBtn = document.getElementById("exampleInputEmail1"); +var yourName = document.getElementById("example-text-input"); +var describeYourself = document.getElementById("exampleTextarea"); + +function pressSubmitBtn(submit) { + if ( + emailBtn.value.length > 0 && + emailBtn.value.includes("@") && + yourName.value.length > 0 && + describeYourself.value.length > 0 + ) { + submit.preventDefault(); + alert("Thanks for filling out the form!"); + emailBtn.value = ""; + nameBtn.value = ""; + describtionBtn.value = ""; + } else if ( + emailBtn.value.length <= 0 || + (yourName.value.length <= 0 && describeYourself.value.length <= 0) + ) { + emailBtn.style.backgroundColor = `red`; + yourName.style.backgroundColor = `red`; + describeYourself.style.backgroundColor = `red`; + } +} +submitBtn.addEventListener("click", pressSubmitBtn); From 85c41bc782be3c62f8e619021fcce72b006197f6 Mon Sep 17 00:00:00 2001 From: Hedyeh Date: Fri, 10 Jul 2020 17:26:42 +0100 Subject: [PATCH 5/5] Hedyeh-week-9 --- .../mandatory/1-practice/2-code-reading.md | 3 + .../Homework/mandatory/1-practice/index.html | 24 + .../Homework/mandatory/1-practice/script.js | 54 ++ .../Homework/mandatory/1-practice/skycons.js | 895 ++++++++++++++++++ .../Homework/mandatory/1-practice/style.css | 38 + .../mandatory/2-exercises/1-shopping-cart.js | 10 + .../mandatory/2-exercises/2-convertion.js | 9 + .../Homework/mandatory/2-exercises/3-atm.js | 24 +- .../mandatory/2-exercises/4-music-player.js | 67 +- 9 files changed, 1099 insertions(+), 25 deletions(-) create mode 100644 week-9/Homework/mandatory/1-practice/index.html create mode 100644 week-9/Homework/mandatory/1-practice/script.js create mode 100644 week-9/Homework/mandatory/1-practice/skycons.js create mode 100644 week-9/Homework/mandatory/1-practice/style.css diff --git a/week-9/Homework/mandatory/1-practice/2-code-reading.md b/week-9/Homework/mandatory/1-practice/2-code-reading.md index 295964e8d..9d862049d 100644 --- a/week-9/Homework/mandatory/1-practice/2-code-reading.md +++ b/week-9/Homework/mandatory/1-practice/2-code-reading.md @@ -14,6 +14,7 @@ Take a look at the following code: ``` Explain why line 4 and line 6 output different numbers. +Because line 4 will print Local variable (which x is defined again) which is 2 but line 6 will print global variable which is 1 ## Question 2 @@ -33,6 +34,7 @@ console.log(y) ``` What will be the output of this code. Explain your answer in 50 words or less. +line 32 print 10 and undefined because line 28 print 10 and y will return as undefined ,line 33 dosen't print anything because y is not defined globally. ## Question 3 @@ -61,3 +63,4 @@ console.log(y); ``` What will be the output of this code. Explain your answer in 50 words or less. +9 and {x:10} because in line 50 it console.log (x) which is 9 and in line 60 it console.log(y) which is {x:9} diff --git a/week-9/Homework/mandatory/1-practice/index.html b/week-9/Homework/mandatory/1-practice/index.html new file mode 100644 index 000000000..d19749d58 --- /dev/null +++ b/week-9/Homework/mandatory/1-practice/index.html @@ -0,0 +1,24 @@ + + + + + + Wheather App + + + +
+

Timezone

+ +
+
+
+

34

+ F +
+
It's cold
+
+ + + + diff --git a/week-9/Homework/mandatory/1-practice/script.js b/week-9/Homework/mandatory/1-practice/script.js new file mode 100644 index 000000000..f3d88315c --- /dev/null +++ b/week-9/Homework/mandatory/1-practice/script.js @@ -0,0 +1,54 @@ +window.addEventListener("load", () => { + let lat; + let long; + let tempDescription = document.querySelector(".tempreture-description"); + let tempDegree = document.querySelector(".tempreture-degree"); + let locationTimezone = document.querySelector(".location-zone"); + let tempretureSection = document.querySelector(".tempreture"); + const tempretureSpan = document.querySelector(".tempreture span"); + + if (navigator.geolocation) { + navigator.geolocation.getCurrentPosition((position) => { + console.log(position); + long = position.coords.longitude; + lat = position.coords.latitude; + const proxy = " https://cors-anywhere.herokuapp.com/"; + const api = `${proxy}https://api.darksky.net/forecast/fd9d9c6418c23d94745b836767721ad1/${lat},${long}`; + fetch(api) + .then((response) => { + return response.json(); + }) + .then((data) => { + console.log(data); + const { temperature, summary, icon } = data.currently; + // const { description, icon } = data.current.weather; + + tempDegree.textContent = temperature; + tempDescription.textContent = summary; + locationTimezone.textContent = data.timezone; + //formulla for celcius + let celsius = (temperature - 32) * (5 / 9); + + //set Icon + setIcon(icon, document.querySelector(".icon")); + + //change tempreture to celsius/farenheit + tempretureSection.addEventListener("click", () => { + if (tempretureSpan.textContent === "F") { + tempretureSpan.textContent = "C"; + tempDegree.textContent = Math.floor(celsius); + } else { + tempretureSpan.textContent = "F"; + tempDegree.textContent = temperature; + } + }); + }); + }); + } + function setIcon(icon, iconId) { + const skycons = new Skycons({ color: "white" }); + const currentIcon = icon.replace(/-/g, "_").toUpperCase(); + skycons.play(); + return skycons.set(iconId, Skycons[currentIcon]); + } +}); diff --git a/week-9/Homework/mandatory/1-practice/skycons.js b/week-9/Homework/mandatory/1-practice/skycons.js new file mode 100644 index 000000000..d28627268 --- /dev/null +++ b/week-9/Homework/mandatory/1-practice/skycons.js @@ -0,0 +1,895 @@ +(function (global) { + "use strict"; + + /* Set up a RequestAnimationFrame shim so we can animate efficiently FOR + * GREAT JUSTICE. */ + var requestInterval, cancelInterval; + + (function () { + var raf = + global.requestAnimationFrame || + global.webkitRequestAnimationFrame || + global.mozRequestAnimationFrame || + global.oRequestAnimationFrame || + global.msRequestAnimationFrame, + caf = + global.cancelAnimationFrame || + global.webkitCancelAnimationFrame || + global.mozCancelAnimationFrame || + global.oCancelAnimationFrame || + global.msCancelAnimationFrame; + + if (raf && caf) { + requestInterval = function (fn) { + var handle = { value: null }; + + function loop() { + handle.value = raf(loop); + fn(); + } + + loop(); + return handle; + }; + + cancelInterval = function (handle) { + caf(handle.value); + }; + } else { + requestInterval = setInterval; + cancelInterval = clearInterval; + } + })(); + + /* Catmull-rom spline stuffs. */ + /* + function upsample(n, spline) { + var polyline = [], + len = spline.length, + bx = spline[0], + by = spline[1], + cx = spline[2], + cy = spline[3], + dx = spline[4], + dy = spline[5], + i, j, ax, ay, px, qx, rx, sx, py, qy, ry, sy, t; + + for(i = 6; i !== spline.length; i += 2) { + ax = bx; + bx = cx; + cx = dx; + dx = spline[i ]; + px = -0.5 * ax + 1.5 * bx - 1.5 * cx + 0.5 * dx; + qx = ax - 2.5 * bx + 2.0 * cx - 0.5 * dx; + rx = -0.5 * ax + 0.5 * cx ; + sx = bx ; + + ay = by; + by = cy; + cy = dy; + dy = spline[i + 1]; + py = -0.5 * ay + 1.5 * by - 1.5 * cy + 0.5 * dy; + qy = ay - 2.5 * by + 2.0 * cy - 0.5 * dy; + ry = -0.5 * ay + 0.5 * cy ; + sy = by ; + + for(j = 0; j !== n; ++j) { + t = j / n; + + polyline.push( + ((px * t + qx) * t + rx) * t + sx, + ((py * t + qy) * t + ry) * t + sy + ); + } + } + + polyline.push( + px + qx + rx + sx, + py + qy + ry + sy + ); + + return polyline; + } + + function downsample(n, polyline) { + var len = 0, + i, dx, dy; + + for(i = 2; i !== polyline.length; i += 2) { + dx = polyline[i ] - polyline[i - 2]; + dy = polyline[i + 1] - polyline[i - 1]; + len += Math.sqrt(dx * dx + dy * dy); + } + + len /= n; + + var small = [], + target = len, + min = 0, + max, t; + + small.push(polyline[0], polyline[1]); + + for(i = 2; i !== polyline.length; i += 2) { + dx = polyline[i ] - polyline[i - 2]; + dy = polyline[i + 1] - polyline[i - 1]; + max = min + Math.sqrt(dx * dx + dy * dy); + + if(max > target) { + t = (target - min) / (max - min); + + small.push( + polyline[i - 2] + dx * t, + polyline[i - 1] + dy * t + ); + + target += len; + } + + min = max; + } + + small.push(polyline[polyline.length - 2], polyline[polyline.length - 1]); + + return small; + } + */ + + /* Define skycon things. */ + /* FIXME: I'm *really really* sorry that this code is so gross. Really, I am. + * I'll try to clean it up eventually! Promise! */ + var KEYFRAME = 500, + STROKE = 0.08, + TAU = 2.0 * Math.PI, + TWO_OVER_SQRT_2 = 2.0 / Math.sqrt(2); + + function circle(ctx, x, y, r) { + ctx.beginPath(); + ctx.arc(x, y, r, 0, TAU, false); + ctx.fill(); + } + + function line(ctx, ax, ay, bx, by) { + ctx.beginPath(); + ctx.moveTo(ax, ay); + ctx.lineTo(bx, by); + ctx.stroke(); + } + + function puff(ctx, t, cx, cy, rx, ry, rmin, rmax) { + var c = Math.cos(t * TAU), + s = Math.sin(t * TAU); + + rmax -= rmin; + + circle( + ctx, + cx - s * rx, + cy + c * ry + rmax * 0.5, + rmin + (1 - c * 0.5) * rmax + ); + } + + function puffs(ctx, t, cx, cy, rx, ry, rmin, rmax) { + var i; + + for (i = 5; i--; ) puff(ctx, t + i / 5, cx, cy, rx, ry, rmin, rmax); + } + + function cloud(ctx, t, cx, cy, cw, s, color) { + t /= 30000; + + var a = cw * 0.21, + b = cw * 0.12, + c = cw * 0.24, + d = cw * 0.28; + + ctx.fillStyle = color; + puffs(ctx, t, cx, cy, a, b, c, d); + + ctx.globalCompositeOperation = "destination-out"; + puffs(ctx, t, cx, cy, a, b, c - s, d - s); + ctx.globalCompositeOperation = "source-over"; + } + + function sun(ctx, t, cx, cy, cw, s, color) { + t /= 120000; + + var a = cw * 0.25 - s * 0.5, + b = cw * 0.32 + s * 0.5, + c = cw * 0.5 - s * 0.5, + i, + p, + cos, + sin; + + ctx.strokeStyle = color; + ctx.lineWidth = s; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + + ctx.beginPath(); + ctx.arc(cx, cy, a, 0, TAU, false); + ctx.stroke(); + + for (i = 8; i--; ) { + p = (t + i / 8) * TAU; + cos = Math.cos(p); + sin = Math.sin(p); + line(ctx, cx + cos * b, cy + sin * b, cx + cos * c, cy + sin * c); + } + } + + function moon(ctx, t, cx, cy, cw, s, color) { + t /= 15000; + + var a = cw * 0.29 - s * 0.5, + b = cw * 0.05, + c = Math.cos(t * TAU), + p = (c * TAU) / -16; + + ctx.strokeStyle = color; + ctx.lineWidth = s; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + + cx += c * b; + + ctx.beginPath(); + ctx.arc(cx, cy, a, p + TAU / 8, p + (TAU * 7) / 8, false); + ctx.arc( + cx + Math.cos(p) * a * TWO_OVER_SQRT_2, + cy + Math.sin(p) * a * TWO_OVER_SQRT_2, + a, + p + (TAU * 5) / 8, + p + (TAU * 3) / 8, + true + ); + ctx.closePath(); + ctx.stroke(); + } + + function rain(ctx, t, cx, cy, cw, s, color) { + t /= 1350; + + var a = cw * 0.16, + b = (TAU * 11) / 12, + c = (TAU * 7) / 12, + i, + p, + x, + y; + + ctx.fillStyle = color; + + for (i = 4; i--; ) { + p = (t + i / 4) % 1; + x = cx + ((i - 1.5) / 1.5) * (i === 1 || i === 2 ? -1 : 1) * a; + y = cy + p * p * cw; + ctx.beginPath(); + ctx.moveTo(x, y - s * 1.5); + ctx.arc(x, y, s * 0.75, b, c, false); + ctx.fill(); + } + } + + function sleet(ctx, t, cx, cy, cw, s, color) { + t /= 750; + + var a = cw * 0.1875, + i, + p, + x, + y; + + ctx.strokeStyle = color; + ctx.lineWidth = s * 0.5; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + + for (i = 4; i--; ) { + p = (t + i / 4) % 1; + x = + Math.floor(cx + ((i - 1.5) / 1.5) * (i === 1 || i === 2 ? -1 : 1) * a) + + 0.5; + y = cy + p * cw; + line(ctx, x, y - s * 1.5, x, y + s * 1.5); + } + } + + function snow(ctx, t, cx, cy, cw, s, color) { + t /= 3000; + + var a = cw * 0.16, + b = s * 0.75, + u = t * TAU * 0.7, + ux = Math.cos(u) * b, + uy = Math.sin(u) * b, + v = u + TAU / 3, + vx = Math.cos(v) * b, + vy = Math.sin(v) * b, + w = u + (TAU * 2) / 3, + wx = Math.cos(w) * b, + wy = Math.sin(w) * b, + i, + p, + x, + y; + + ctx.strokeStyle = color; + ctx.lineWidth = s * 0.5; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + + for (i = 4; i--; ) { + p = (t + i / 4) % 1; + x = cx + Math.sin((p + i / 4) * TAU) * a; + y = cy + p * cw; + + line(ctx, x - ux, y - uy, x + ux, y + uy); + line(ctx, x - vx, y - vy, x + vx, y + vy); + line(ctx, x - wx, y - wy, x + wx, y + wy); + } + } + + function fogbank(ctx, t, cx, cy, cw, s, color) { + t /= 30000; + + var a = cw * 0.21, + b = cw * 0.06, + c = cw * 0.21, + d = cw * 0.28; + + ctx.fillStyle = color; + puffs(ctx, t, cx, cy, a, b, c, d); + + ctx.globalCompositeOperation = "destination-out"; + puffs(ctx, t, cx, cy, a, b, c - s, d - s); + ctx.globalCompositeOperation = "source-over"; + } + + /* + var WIND_PATHS = [ + downsample(63, upsample(8, [ + -1.00, -0.28, + -0.75, -0.18, + -0.50, 0.12, + -0.20, 0.12, + -0.04, -0.04, + -0.07, -0.18, + -0.19, -0.18, + -0.23, -0.05, + -0.12, 0.11, + 0.02, 0.16, + 0.20, 0.15, + 0.50, 0.07, + 0.75, 0.18, + 1.00, 0.28 + ])), + downsample(31, upsample(16, [ + -1.00, -0.10, + -0.75, 0.00, + -0.50, 0.10, + -0.25, 0.14, + 0.00, 0.10, + 0.25, 0.00, + 0.50, -0.10, + 0.75, -0.14, + 1.00, -0.10 + ])) + ]; + */ + + var WIND_PATHS = [ + [ + -0.75, + -0.18, + -0.7219, + -0.1527, + -0.6971, + -0.1225, + -0.6739, + -0.091, + -0.6516, + -0.0588, + -0.6298, + -0.0262, + -0.6083, + 0.0065, + -0.5868, + 0.0396, + -0.5643, + 0.0731, + -0.5372, + 0.1041, + -0.5033, + 0.1259, + -0.4662, + 0.1406, + -0.4275, + 0.1493, + -0.3881, + 0.153, + -0.3487, + 0.1526, + -0.3095, + 0.1488, + -0.2708, + 0.1421, + -0.2319, + 0.1342, + -0.1943, + 0.1217, + -0.16, + 0.1025, + -0.129, + 0.0785, + -0.1012, + 0.0509, + -0.0764, + 0.0206, + -0.0547, + -0.012, + -0.0378, + -0.0472, + -0.0324, + -0.0857, + -0.0389, + -0.1241, + -0.0546, + -0.1599, + -0.0814, + -0.1876, + -0.1193, + -0.1964, + -0.1582, + -0.1935, + -0.1931, + -0.1769, + -0.2157, + -0.1453, + -0.229, + -0.1085, + -0.2327, + -0.0697, + -0.224, + -0.0317, + -0.2064, + 0.0033, + -0.1853, + 0.0362, + -0.1613, + 0.0672, + -0.135, + 0.0961, + -0.1051, + 0.1213, + -0.0706, + 0.1397, + -0.0332, + 0.1512, + 0.0053, + 0.158, + 0.0442, + 0.1624, + 0.0833, + 0.1636, + 0.1224, + 0.1615, + 0.1613, + 0.1565, + 0.1999, + 0.15, + 0.2378, + 0.1402, + 0.2749, + 0.1279, + 0.3118, + 0.1147, + 0.3487, + 0.1015, + 0.3858, + 0.0892, + 0.4236, + 0.0787, + 0.4621, + 0.0715, + 0.5012, + 0.0702, + 0.5398, + 0.0766, + 0.5768, + 0.089, + 0.6123, + 0.1055, + 0.6466, + 0.1244, + 0.6805, + 0.144, + 0.7147, + 0.163, + 0.75, + 0.18, + ], + [ + -0.75, + 0.0, + -0.7033, + 0.0195, + -0.6569, + 0.0399, + -0.6104, + 0.06, + -0.5634, + 0.0789, + -0.5155, + 0.0954, + -0.4667, + 0.1089, + -0.4174, + 0.1206, + -0.3676, + 0.1299, + -0.3174, + 0.1365, + -0.2669, + 0.1398, + -0.2162, + 0.1391, + -0.1658, + 0.1347, + -0.1157, + 0.1271, + -0.0661, + 0.1169, + -0.017, + 0.1046, + 0.0316, + 0.0903, + 0.0791, + 0.0728, + 0.1259, + 0.0534, + 0.1723, + 0.0331, + 0.2188, + 0.0129, + 0.2656, + -0.0064, + 0.3122, + -0.0263, + 0.3586, + -0.0466, + 0.4052, + -0.0665, + 0.4525, + -0.0847, + 0.5007, + -0.1002, + 0.5497, + -0.113, + 0.5991, + -0.124, + 0.6491, + -0.1325, + 0.6994, + -0.138, + 0.75, + -0.14, + ], + ], + WIND_OFFSETS = [ + { start: 0.36, end: 0.11 }, + { start: 0.56, end: 0.16 }, + ]; + + function leaf(ctx, t, x, y, cw, s, color) { + var a = cw / 8, + b = a / 3, + c = 2 * b, + d = (t % 1) * TAU, + e = Math.cos(d), + f = Math.sin(d); + + ctx.fillStyle = color; + ctx.strokeStyle = color; + ctx.lineWidth = s; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + + ctx.beginPath(); + ctx.arc(x, y, a, d, d + Math.PI, false); + ctx.arc(x - b * e, y - b * f, c, d + Math.PI, d, false); + ctx.arc(x + c * e, y + c * f, b, d + Math.PI, d, true); + ctx.globalCompositeOperation = "destination-out"; + ctx.fill(); + ctx.globalCompositeOperation = "source-over"; + ctx.stroke(); + } + + function swoosh(ctx, t, cx, cy, cw, s, index, total, color) { + t /= 2500; + + var path = WIND_PATHS[index], + a = (t + index - WIND_OFFSETS[index].start) % total, + c = (t + index - WIND_OFFSETS[index].end) % total, + e = (t + index) % total, + b, + d, + f, + i; + + ctx.strokeStyle = color; + ctx.lineWidth = s; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + + if (a < 1) { + ctx.beginPath(); + + a *= path.length / 2 - 1; + b = Math.floor(a); + a -= b; + b *= 2; + b += 2; + + ctx.moveTo( + cx + (path[b - 2] * (1 - a) + path[b] * a) * cw, + cy + (path[b - 1] * (1 - a) + path[b + 1] * a) * cw + ); + + if (c < 1) { + c *= path.length / 2 - 1; + d = Math.floor(c); + c -= d; + d *= 2; + d += 2; + + for (i = b; i !== d; i += 2) + ctx.lineTo(cx + path[i] * cw, cy + path[i + 1] * cw); + + ctx.lineTo( + cx + (path[d - 2] * (1 - c) + path[d] * c) * cw, + cy + (path[d - 1] * (1 - c) + path[d + 1] * c) * cw + ); + } else + for (i = b; i !== path.length; i += 2) + ctx.lineTo(cx + path[i] * cw, cy + path[i + 1] * cw); + + ctx.stroke(); + } else if (c < 1) { + ctx.beginPath(); + + c *= path.length / 2 - 1; + d = Math.floor(c); + c -= d; + d *= 2; + d += 2; + + ctx.moveTo(cx + path[0] * cw, cy + path[1] * cw); + + for (i = 2; i !== d; i += 2) + ctx.lineTo(cx + path[i] * cw, cy + path[i + 1] * cw); + + ctx.lineTo( + cx + (path[d - 2] * (1 - c) + path[d] * c) * cw, + cy + (path[d - 1] * (1 - c) + path[d + 1] * c) * cw + ); + + ctx.stroke(); + } + + if (e < 1) { + e *= path.length / 2 - 1; + f = Math.floor(e); + e -= f; + f *= 2; + f += 2; + + leaf( + ctx, + t, + cx + (path[f - 2] * (1 - e) + path[f] * e) * cw, + cy + (path[f - 1] * (1 - e) + path[f + 1] * e) * cw, + cw, + s, + color + ); + } + } + + var Skycons = function (opts) { + this.list = []; + this.interval = null; + this.color = opts && opts.color ? opts.color : "black"; + this.resizeClear = !!(opts && opts.resizeClear); + }; + + Skycons.CLEAR_DAY = function (ctx, t, color) { + var w = ctx.canvas.width, + h = ctx.canvas.height, + s = Math.min(w, h); + + sun(ctx, t, w * 0.5, h * 0.5, s, s * STROKE, color); + }; + + Skycons.CLEAR_NIGHT = function (ctx, t, color) { + var w = ctx.canvas.width, + h = ctx.canvas.height, + s = Math.min(w, h); + + moon(ctx, t, w * 0.5, h * 0.5, s, s * STROKE, color); + }; + + Skycons.PARTLY_CLOUDY_DAY = function (ctx, t, color) { + var w = ctx.canvas.width, + h = ctx.canvas.height, + s = Math.min(w, h); + + sun(ctx, t, w * 0.625, h * 0.375, s * 0.75, s * STROKE, color); + cloud(ctx, t, w * 0.375, h * 0.625, s * 0.75, s * STROKE, color); + }; + + Skycons.PARTLY_CLOUDY_NIGHT = function (ctx, t, color) { + var w = ctx.canvas.width, + h = ctx.canvas.height, + s = Math.min(w, h); + + moon(ctx, t, w * 0.667, h * 0.375, s * 0.75, s * STROKE, color); + cloud(ctx, t, w * 0.375, h * 0.625, s * 0.75, s * STROKE, color); + }; + + Skycons.CLOUDY = function (ctx, t, color) { + var w = ctx.canvas.width, + h = ctx.canvas.height, + s = Math.min(w, h); + + cloud(ctx, t, w * 0.5, h * 0.5, s, s * STROKE, color); + }; + + Skycons.RAIN = function (ctx, t, color) { + var w = ctx.canvas.width, + h = ctx.canvas.height, + s = Math.min(w, h); + + rain(ctx, t, w * 0.5, h * 0.37, s * 0.9, s * STROKE, color); + cloud(ctx, t, w * 0.5, h * 0.37, s * 0.9, s * STROKE, color); + }; + + Skycons.SLEET = function (ctx, t, color) { + var w = ctx.canvas.width, + h = ctx.canvas.height, + s = Math.min(w, h); + + sleet(ctx, t, w * 0.5, h * 0.37, s * 0.9, s * STROKE, color); + cloud(ctx, t, w * 0.5, h * 0.37, s * 0.9, s * STROKE, color); + }; + + Skycons.SNOW = function (ctx, t, color) { + var w = ctx.canvas.width, + h = ctx.canvas.height, + s = Math.min(w, h); + + snow(ctx, t, w * 0.5, h * 0.37, s * 0.9, s * STROKE, color); + cloud(ctx, t, w * 0.5, h * 0.37, s * 0.9, s * STROKE, color); + }; + + Skycons.WIND = function (ctx, t, color) { + var w = ctx.canvas.width, + h = ctx.canvas.height, + s = Math.min(w, h); + + swoosh(ctx, t, w * 0.5, h * 0.5, s, s * STROKE, 0, 2, color); + swoosh(ctx, t, w * 0.5, h * 0.5, s, s * STROKE, 1, 2, color); + }; + + Skycons.FOG = function (ctx, t, color) { + var w = ctx.canvas.width, + h = ctx.canvas.height, + s = Math.min(w, h), + k = s * STROKE; + + fogbank(ctx, t, w * 0.5, h * 0.32, s * 0.75, k, color); + + t /= 5000; + + var a = Math.cos(t * TAU) * s * 0.02, + b = Math.cos((t + 0.25) * TAU) * s * 0.02, + c = Math.cos((t + 0.5) * TAU) * s * 0.02, + d = Math.cos((t + 0.75) * TAU) * s * 0.02, + n = h * 0.936, + e = Math.floor(n - k * 0.5) + 0.5, + f = Math.floor(n - k * 2.5) + 0.5; + + ctx.strokeStyle = color; + ctx.lineWidth = k; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + + line(ctx, a + w * 0.2 + k * 0.5, e, b + w * 0.8 - k * 0.5, e); + line(ctx, c + w * 0.2 + k * 0.5, f, d + w * 0.8 - k * 0.5, f); + }; + + Skycons.prototype = { + _determineDrawingFunction: function (draw) { + if (typeof draw === "string") + draw = Skycons[draw.toUpperCase().replace(/-/g, "_")] || null; + + return draw; + }, + add: function (el, draw) { + var obj; + + if (typeof el === "string") el = document.getElementById(el); + + // Does nothing if canvas name doesn't exists + if (el === null || el === undefined) return; + + draw = this._determineDrawingFunction(draw); + + // Does nothing if the draw function isn't actually a function + if (typeof draw !== "function") return; + + obj = { + element: el, + context: el.getContext("2d"), + drawing: draw, + }; + + this.list.push(obj); + this.draw(obj, KEYFRAME); + }, + set: function (el, draw) { + var i; + + if (typeof el === "string") el = document.getElementById(el); + + for (i = this.list.length; i--; ) + if (this.list[i].element === el) { + this.list[i].drawing = this._determineDrawingFunction(draw); + this.draw(this.list[i], KEYFRAME); + return; + } + + this.add(el, draw); + }, + remove: function (el) { + var i; + + if (typeof el === "string") el = document.getElementById(el); + + for (i = this.list.length; i--; ) + if (this.list[i].element === el) { + this.list.splice(i, 1); + return; + } + }, + draw: function (obj, time) { + var canvas = obj.context.canvas; + + if (this.resizeClear) canvas.width = canvas.width; + else obj.context.clearRect(0, 0, canvas.width, canvas.height); + + obj.drawing(obj.context, time, this.color); + }, + play: function () { + var self = this; + + this.pause(); + this.interval = requestInterval(function () { + var now = Date.now(), + i; + + for (i = self.list.length; i--; ) self.draw(self.list[i], now); + }, 1000 / 60); + }, + pause: function () { + if (this.interval) { + cancelInterval(this.interval); + this.interval = null; + } + }, + }; + + global.Skycons = Skycons; +})(this); diff --git a/week-9/Homework/mandatory/1-practice/style.css b/week-9/Homework/mandatory/1-practice/style.css new file mode 100644 index 000000000..ef6e0ccce --- /dev/null +++ b/week-9/Homework/mandatory/1-practice/style.css @@ -0,0 +1,38 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + height: 100vh; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + background: linear-gradient(rgb(47, 150, 28), rgb(30, 140, 67)); + font-family: sans-serif; +} +.location, +.tempreture { + height: 30vh; + width: 50%; + display: flex; + justify-content: space-around; + align-items: center; +} +.tempreture { + flex-direction: column; +} +.degree-section { + display: flex; + align-items: center; + cursor: pointer; +} +.degree-section span { + margin: 10px; + font-size: 20px; +} +.degree-section h2 { + font-size: 40px; +} diff --git a/week-9/Homework/mandatory/2-exercises/1-shopping-cart.js b/week-9/Homework/mandatory/2-exercises/1-shopping-cart.js index d58a05143..6c3fde545 100644 --- a/week-9/Homework/mandatory/2-exercises/1-shopping-cart.js +++ b/week-9/Homework/mandatory/2-exercises/1-shopping-cart.js @@ -10,10 +10,20 @@ The output of running your code should be: */ class ShoppingCart { + constructor() { + this.shopping = []; + } + + addItem(item) { + this.shopping.push(item); + } // Add your code here cartContains() { // Use console.log() to output everything contained in your cart + console.log( + `Your cart has ${this.shopping.length} items: ${this.shopping}` + ); } } diff --git a/week-9/Homework/mandatory/2-exercises/2-convertion.js b/week-9/Homework/mandatory/2-exercises/2-convertion.js index d70ca4fcd..1c8b40567 100644 --- a/week-9/Homework/mandatory/2-exercises/2-convertion.js +++ b/week-9/Homework/mandatory/2-exercises/2-convertion.js @@ -23,6 +23,15 @@ // Write your code here +class Person { + constructor(name) { + this.name = name; + } + greeting() { + console.log("Hi! I'm " + this.name + "."); + } +} + // Do not edit this section const simon = new Person("simon"); console.log(simon.name); diff --git a/week-9/Homework/mandatory/2-exercises/3-atm.js b/week-9/Homework/mandatory/2-exercises/3-atm.js index 768bce40e..b9b27e1de 100644 --- a/week-9/Homework/mandatory/2-exercises/3-atm.js +++ b/week-9/Homework/mandatory/2-exercises/3-atm.js @@ -12,8 +12,26 @@ */ class ATM { - // Add your code here - + constructor() { + this.balance = 100.0; + } + make_deposit(amount) { + if (amount > 0) { + this.balance += amount; + } else { + console.log(`Please enter a positive number`); + } + } + check_balance() { + console.log(`You have ${this.balance} in your account`); + } + make_withdrawl(amount) { + if (this.balance > amount && amount > 0) { + this.balance -= amount; + } else { + console.log(`Sorry, You don't have enough money in your account`); + } + } } let atm = new ATM(); // Create the ATM @@ -22,4 +40,4 @@ atm.make_deposit(200); atm.check_balance(); atm.make_withdrawl(100); -atm.make_withdrawl(500); // Your ATM should be able to handle this scenario \ No newline at end of file +atm.make_withdrawl(500); // Your ATM should be able to handle this scenario diff --git a/week-9/Homework/mandatory/2-exercises/4-music-player.js b/week-9/Homework/mandatory/2-exercises/4-music-player.js index b820e5bf3..d000a5176 100644 --- a/week-9/Homework/mandatory/2-exercises/4-music-player.js +++ b/week-9/Homework/mandatory/2-exercises/4-music-player.js @@ -18,36 +18,59 @@ This means the order the songs are played in will be random, but each song will */ - class MusicPlayer { - // Add your code here - + constructor() { + this.i = 0; + this.playList = []; + } + add(music, singer) { + this.playList.push(`${music} by ${singer}`); + } + play() { + if (this.i > this.playList.length || this.i < 0) { + console.log(`there is no song to play`); + } else { + console.log(`Currently Playing: ${this.playList[this.i]}`); + } + } + skip() { + if (this.i < this.playList.length - 1) { + this.i++; + this.play(); + } else { + console.log(`There isn't any song to play`); + } + } + + previous() { + this.i--; + if (this.i < 0) { + this.i = this.playList.length - 1; + } + this.play(); + } + + shuffle() { + let random = Math.floor(Math.random() * this.playList.length); + this.i = random; + this.play(); + } } let myMusicPlayer = new MusicPlayer(); // Create an empty playlist // Add some songs to your playlist -myMusicPlayer.add("Bohemian Rhapsody","Queen"); -myMusicPlayer.add("Yesterday","The Beatles"); -myMusicPlayer.add("Vogue","Madonna"); - -myMusicPlayer.play(); // Output: "Currently playing: Bohemian Rhapsody by Queen" - -myMusicPlayer.skip(); // Output: "Currently playing: Yesterday by The Beatles" - -myMusicPlayer.previous(); // Output: "Currently playing: Bohemian Rhapsody by Queen" - -myMusicPlayer.skip(); // Output: "Currently playing: Yesterday by The Beatles" - -myMusicPlayer.skip(); // Output: "Currently playing: Vogue by Madonna" - - - - - - +myMusicPlayer.add("Bohemian Rhapsody", "Queen"); +myMusicPlayer.add("Yesterday", "The Beatles"); +myMusicPlayer.add("Vogue", "Madonna"); +myMusicPlayer.play(); // Output: "Currently playing: Bohemian Rhapsody by Queen" +myMusicPlayer.skip(); // Output: "Currently playing: Yesterday by The Beatles" +myMusicPlayer.previous(); // Output: "Currently playing: Bohemian Rhapsody by Queen" +myMusicPlayer.skip(); // Output: "Currently playing: Yesterday by The Beatles" +myMusicPlayer.skip(); // Output: "Currently playing: Vogue by Madonna" +myMusicPlayer.shuffle();