Skip to content
This repository was archived by the owner on Jan 14, 2024. It is now read-only.

London10-Afsha-Hossain-JS-Core1-Coursework-Week3 #257

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions 1-exercises/A-undefined/exercise.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,28 @@
let a;
console.log(a);

// The output of the example code console.log(a); will be undefined.
// We see undefined because the variable a has been declared but not assigned any value.
// In JavaScript, when a variable is declared but not assigned a value, its default value is undefined.
// So, when we log the value of a to the console, you will see undefined printed.


// Example 2
function sayHello() {
let message = "Hello";
}


let hello = sayHello();
console.log(hello);

// The output in the example contains undefined because the sayHello function does not return any value explicitly.
// When a function is called, it can return a value using the return keyword.
// If the return keyword is not used in the function, the function will return undefined by default.
// In the example, the sayHello function prints "Hello" to the console but does not return any value.
// When the sayHello function is assigned to the result variable, the result variable is assigned the value of undefined because that is the value that the sayHello function returns by default.
// When the result variable is printed to the console, it will display undefined because that is the value that was assigned to it when the sayHello function was called.


// Example 3
function sayHelloToUser(user) {
Expand All @@ -30,7 +43,21 @@ function sayHelloToUser(user) {

sayHelloToUser();

// The output contains undefined because the sayHelloToUser() function expects an argument user, but when it's called without any argument like sayHelloToUser(), the user parameter is undefined.
// The console.log() statement inside the function uses the user parameter to construct the message to be logged, so when user is undefined, the message will include undefined as the value of user.
// However, since the function doesn't have a return statement, its return value is undefined by default.
// Therefore, when you call sayHelloToUser() without any argument, it logs the message "Hello undefined" to the console, but the return value of the function is undefined.
// So the complete output of this code would be:
// undefined
// Hello undefined
// The first line is the message logged by the console.log() statement inside the sayHelloToUser() function, and the second line is the return value of the sayHelloToUser() function, which is undefined.



// Example 4
let arr = [1,2,3];
console.log(arr[3]);

// The output in the example below contains undefined because letters is an array with three elements, indexed from 0 to 2.
// When we try to access the element at index 3 (arr[3]), which is beyond the last index of the letters array, JavaScript returns undefined because there is no value at that index.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice explanation.

4 changes: 2 additions & 2 deletions 1-exercises/B-array-literals/exercise.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
Declare some variables assigned to arrays of values
*/

let numbers = []; // add numbers from 1 to 10 into this array
let mentors; // Create an array with the names of the mentors: Daniel, Irina and Rares
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // add numbers from 1 to 10 into this array
let mentors = ["Daniel", "Irina", "Rares"]; // Create an array with the names of the mentors: Daniel, Irina and Rares

/*
DO NOT EDIT BELOW THIS LINE
Expand Down
5 changes: 3 additions & 2 deletions 1-exercises/C-array-get-set/exercise.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
*/

function first(arr) {
return; // complete this statement
return arr[0]; // complete this statement
}

function last(arr) {
return; // complete this statement
return arr[arr.length - 1]; // complete this statement
}


/*
DO NOT EDIT BELOW THIS LINE
--------------------------- */
Expand Down
2 changes: 2 additions & 0 deletions 1-exercises/C-array-get-set/exercises2.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

let numbers = [1, 2, 3]; // Don't change this array literal declaration

let count = numbers.push(4);

/*
DO NOT EDIT BELOW THIS LINE
--------------------------- */
Expand Down
8 changes: 8 additions & 0 deletions 1-exercises/D-for-loop/exercise.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ const AGES = [

// TODO - Write for loop code here

for (i = 0; i < WRITERS.length; i++) {
console.log(`${WRITERS[i]} is ${AGES[i]} years old`);
}

/*
The output should look something like this:

Expand All @@ -37,3 +41,7 @@ Jane Austen is 41 years old
Bell Hooks is 63 years old
Yukiko Motoya is 49 years old
*/




9 changes: 8 additions & 1 deletion 1-exercises/E-while-loop-with-array/exercise.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,15 @@ const BIRTHDAYS = [
"November 15th"
];

function findFirstJulyBDay(birthdays) {
function findFirstJulyBDay(BIRTHDAYS) {
// TODO
let i = 0;
while (i < BIRTHDAYS.length) {
if (BIRTHDAYS[i].startsWith("July")) {
return BIRTHDAYS[i];
}
i++;
}
}

console.log(findFirstJulyBDay(BIRTHDAYS)); // should output "July 11th"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work, consice and good.

17 changes: 17 additions & 0 deletions 2-mandatory/1-weather-report.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,19 @@
- Hint: you can call the temperatureService function from your function
*/

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks perfect 👍

// 1. Create a new empty array
// 2. Loop through the cities, and for each city:
// a. Create a new string for the weather report of that city
// b. Add that new string into the array
// 3. Return the array

function getTemperatureReport(cities) {
let arr = [];
for (let city of cities) {
let weatherReport = `The temperature in ${city} is ${temperatureService(city)} degrees`;
arr.push(weatherReport);
}
return arr;
// TODO
}

Expand All @@ -32,6 +44,11 @@ function temperatureService(city) {
return temparatureMap.get(city);
}

test("should return array of same length as argument", () => {
let usersCities = ["London", "Paris", "São Paulo"];
expect(getTemperatureReport(usersCities).length).toEqual(3);
});

test("should return a temperature report for the user's cities", () => {
let usersCities = [
"London",
Expand Down
55 changes: 55 additions & 0 deletions 2-mandatory/2-financial-times.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@
Implement the function below, which will return a new array containing only article titles which will fit.
*/
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This look good!
For extra practice, can you try re-writing this using the filter array method?

function potentialHeadlines(allArticleTitles) {
let newArray = [];
for (let item of allArticleTitles) {
if (item.length <= 65) {
newArray.push(item);
}
}
return newArray;
// TODO
}

Expand All @@ -13,25 +20,72 @@ function potentialHeadlines(allArticleTitles) {
Implement the function below, which returns the title with the fewest words.
(you can assume words will always be seperated by a space)
*/
// ["The", "three", "questions", "that", "dominate", "investment"]
// fewestNumberOfWords = articleSplitter.length;

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a very good attempt 👍 One small improvement:

  • Could you try doing this without using let fewestNumberOfWords = 1000;
  • You could either leave it uninitialised and check for undefined in your loop.. Or you could maybe initialise to the numberOfWords of the first title in the list.

function titleWithFewestWords(allArticleTitles) {
let shortestHeadline;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you could declare 'shortestHeadline' with const keyword instead let

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think shortestHeadline needs to be declared with let here as we are re-assigning a new value to it a few lines later.

let fewestNumberOfWords = 1000;

for (let headline of allArticleTitles) {
let splitArticleTitle = (headline.split(" "));
if (splitArticleTitle.length < fewestNumberOfWords) {
fewestNumberOfWords = splitArticleTitle.length;
shortestHeadline = headline;
}
}
return shortestHeadline;
// TODO
// loop through the headlines
// find number words in the headline
// find number of words in title
// compare the number with
}


/*
The editor of the FT has realised that headlines which have numbers in them get more clicks!
Implement the function below to return a new array containing all the headlines which contain a number.
(Hint: remember that you can also loop through the characters of a string if you need to)
*/

// 1. We are getting array of string. We need to find if the string includes numbers.
// 2. Once we find a number, we will put the string to the new array.
// 3. We are going to return the new array. New array is string with numbers.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice 👍

function headlinesWithNumbers(allArticleTitles) {
let newArrayWithNum = [];
for (const title of allArticleTitles) {
if (/\d/.test(title)) {
newArrayWithNum.push(title);
}
}

return newArrayWithNum;
// TODO
}

// for (character of title) {
// if (character.includes(Number)) {
// newArrayWithNum.push(title)
// }

/*
The Financial Times wants to understand what the average number of characters in an article title is.
Implement the function below to return this number - rounded to the nearest integer.
*/
// 1. We find total characters
// 2. We need to find the number of Article titles.
// 3. We divide (total character) by (number of article titles).
// 4. Round it up

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks very good!

function averageNumberOfCharacters(allArticleTitles) {
// TODO
let totalCharacter = 0;
for (let item of allArticleTitles) {
totalCharacter = totalCharacter + item.length;
}
return Math.round(totalCharacter / allArticleTitles.length);
}


Expand All @@ -50,6 +104,7 @@ const ARTICLE_TITLES = [
"Brussels urges Chile's incoming president to endorse EU trade deal",
];


/* ======= TESTS - DO NOT MODIFY ===== */

test("should only return potential headlines", () => {
Expand Down
68 changes: 63 additions & 5 deletions 2-mandatory/3-stocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,24 @@ const CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS = [
Solve the smaller problems, and then build those solutions back up to solve the larger problem.
Functions can help with this!
*/

// 1. Find the total price of each company stocks in the last 5 days
// 2. Divide the total price by the number of days i.e. 5



Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very good variable names 😄
One question: Do you need to re-calculate the average each time through the loop? Maybe it's enough to just calculate the average once at the end?

function getAveragePrices(closingPricesForAllStocks) {
// TODO
let arrayOfAverageValues = [];
for (let closingPriceEachCompany of closingPricesForAllStocks) {
let sumOfClosingPriceEachCompany = 0;
for (i = 0; i < closingPriceEachCompany.length; i++) {
sumOfClosingPriceEachCompany = sumOfClosingPriceEachCompany + closingPriceEachCompany[i];
averagePriceEachCompany = (sumOfClosingPriceEachCompany / closingPriceEachCompany.length).toFixed(2);
}
averagePricesNumberType = parseFloat(averagePriceEachCompany);
arrayOfAverageValues.push(averagePricesNumberType);
}
return arrayOfAverageValues;
}

/*
Expand All @@ -47,8 +63,18 @@ function getAveragePrices(closingPricesForAllStocks) {
(Apple's price on the 5th day) - (Apple's price on the 1st day) = 172.99 - 179.19 = -6.2
The price change value should be rounded to 2 decimal places, and should be a number (not a string)
*/
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!
One question: Will this code - closingPricesEachcompany[4] - closingPricesEachcompany[0] - still work if we have more than 5 prices in each array? Or less than 5 prices?
Can you think of how to make sure this works for any numbers of prices?


// 1. AAPL (apple) price difference last day - first day = -6.2
//

function getPriceChanges(closingPricesForAllStocks) {
// TODO
let newPriceChangeArray = [];
for (let oneSetOfPrices of closingPricesForAllStocks) {
let priceChange = (oneSetOfPrices[(oneSetOfPrices.length - 1)] - oneSetOfPrices[0]).toFixed(2); //converted to 2 decimal places but it is also converted to string in the process
let priceChangeValues = parseFloat(priceChange); // removing the string values to numbers
newPriceChangeArray.push(priceChangeValues);
}
return newPriceChangeArray;
}

/*
Expand All @@ -63,9 +89,41 @@ function getPriceChanges(closingPricesForAllStocks) {
The stock ticker should be capitalised.
The price should be shown with exactly 2 decimal places.
*/
function highestPriceDescriptions(closingPricesForAllStocks, stocks) {
// TODO
}

// for (i = 0; i < closingPricesForAllStocks.length; i++) {
// let highestPrice = 0;const CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS = [
[179.19, 180.33, 176.28, 175.64, 172.99], // AAPL
[340.69, 342.45, 334.69, 333.20, 327.29], // MSFT
[3384.44, 3393.39, 3421.37, 3420.74, 3408.34], // AMZN
[2951.88, 2958.13, 2938.33, 2928.30, 2869.45], // GOOGL
[1101.30, 1093.94, 1067.00, 1008.87, 938.53] // TSLA

// for (let companyPriceArray of closingPricesForAllStocks) {
// if (companyPriceArray[i] > highestPrice) {
// highestPrice = companyPriceArray[i];
// }
// }
// arrayWithHighestValue.push(highestPrice);

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was a tough one!
Well done for completing it 👏

function highestPriceDescriptions(closingPricesForAllStocks, stocks) {
let highestCompanyStockPrices = [];
let namesOfCompanies = [];
let highestPrice = 0;
for (i = 0; i < closingPricesForAllStocks.length; i++) {
for (let closingPricePerDay of closingPricesForAllStocks[i]) {
if (closingPricePerDay > highestPrice) {
highestPrice = closingPricePerDay;
}
}
let upperStock = stocks[i].toUpperCase();
highestCompanyStockPrices.push(
`The highest price of ${upperStock} in the last 5 days was ${highestPrice.toFixed(2)}`);
highestPrice = 0;
}
return highestCompanyStockPrices;
// return `The highest price of ${stocks} in the last 5 days was ${arrayWithHighestValue[i]}`;
}



/* ======= TESTS - DO NOT MODIFY ===== */
Expand Down
9 changes: 9 additions & 0 deletions 3-extra/2-array-of-objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@
Each title in the resulting array should be the highest rated book in its genre.
*/

// note: Steps to create a function. think about argument. think about input and output and its types. array of object mean array of what type or what type of array.
// blue word before the colon is key or value or property
// we can use teh square bracket
// const books = [{title: "The Lion King"}] // of an array
// const book = {title; "The Lion King"}
// 2 ways to access the value:
// book.title // "The Lion King"
// book["tile"] //"The Lion King"

function getHighestRatedInEachGenre(books) {
// TODO
}
Expand Down