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

London Class 10- Yuliya Hospodar- JavaScript-Core-1-Coursework-Week3 #280

Open
wants to merge 5 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
9 changes: 8 additions & 1 deletion 1-exercises/A-undefined/exercise.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,20 @@
*/

// Example 1
let a;
let = a;
console.log(a);

// In this example an operator "=" was absent

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

let hello = sayHello();
console.log(hello);
// The mistake was inside function body, where return was absent that is why we've seen undefined


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

sayHelloToUser();

// Inside function parameter braces should be parameter when the function is called

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

// When we call array elements via arr[] method we need to consider that index starts from 0 in arr, that's
// we see undefined because we call 4th element
31 changes: 18 additions & 13 deletions 2-mandatory/1-weather-report.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
/*
Imagine we're making a weather app!

We have a list of cities that the user wants to track.
We also already have a temperatureService function which will take a city as a parameter and return a temparature.
/*
Imagine we're making a weather app!
We have a list of cities that the user wants to track.
We also already have a temperatureService function which will take a city as a parameter and return a temparature.

Implement the function below:
- take the array of cities as a parameter
- return an array of strings, which is a statement about the temperature of each city.
For example, "The temperature in London is 10 degrees"
- Hint: you can call the temperatureService function from your function
*/
Implement the function below:
- take the array of cities as a parameter
- return an array of strings, which is a statement about the temperature of each city.
For example, "The temperature in London is 10 degrees"
- Hint: you can call the temperatureService function from your function
*/

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


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

function temperatureService(city) {
Expand Down
56 changes: 52 additions & 4 deletions 2-mandatory/2-financial-times.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@
Implement the function below, which will return a new array containing only article titles which will fit.
*/
function potentialHeadlines(allArticleTitles) {
// TODO
let headlines = [];

for(let title of allArticleTitles) {
if(title.length <= 65) {
headlines.push(title);
}
}

return headlines;
}

/*
Expand All @@ -14,7 +22,21 @@ function potentialHeadlines(allArticleTitles) {
(you can assume words will always be seperated by a space)
*/
function titleWithFewestWords(allArticleTitles) {
// TODO
let fewestWordsSoFar;
let titleWithFewestWords;

for(let title of allArticleTitles) {

// working out the number of words in the title by splitting on the space character
//this will create an array
let shortWords = title.split('').length;

if(fewestWordsSoFar === undefined || shortWords < fewestWordsSoFar) {
fewestWordsSoFar = shortWords;
titleWithFewestWords = title;
}
}
return titleWithFewestWords;
}

/*
Expand All @@ -23,15 +45,41 @@ function titleWithFewestWords(allArticleTitles) {
(Hint: remember that you can also loop through the characters of a string if you need to)
*/
function headlinesWithNumbers(allArticleTitles) {
// TODO
let articlesWithNumbers = [];

for(let title of allArticleTitles) {
//Making use of the new function created below
if (doesTitleContainANumber(title)) {
articlesWithNumbers.push(title);
}
}

return articlesWithNumbers;
}

//Creating another function that helps break this problem down into smaller pieces
function doesTitleContainANumber(titele) {
for(let character of titele) {
if(character >= '0' && character <= '9') {
return true;
}
}
return false;
}


/*
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.
*/
function averageNumberOfCharacters(allArticleTitles) {
// TODO
let totalCharacters = 0;

for(let titele of allArticleTitles) {
totalCharacters +=titele.length;
}

return Math.round(totalCharacters / allArticleTitles.length);
}


Expand Down
103 changes: 100 additions & 3 deletions 2-mandatory/3-stocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,41 @@ 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!
*/

/*
SOLUTION EXPLANATION: This is quite a complex problem and there are several ways to solve it.
I decided to divide the big problem into several smaller ones.
1. In the exercise we are asked to find the average price of EACH stock.
So maybe we can just work out how to get the average price for a single stock.
To do this, I created a separate function called getAveragePricesForStock.
2. We also need to work out how to round a number to 2 decimal places.
There is also a separate function for this called roundTo2Decimals.
3. We can put these smaller solutions together to solve a bigger problem.
The top-level price function getAveragePrices can loop through an array,
and pass each subarray to the getAveragePricesForStock function.
*/
function getAveragePrices(closingPricesForAllStocks) {
// TODO
let averages = [];

for (let pricesForStock of closingPricesForAllStocks) {
averages.push(getAveragePricesForStock(pricesForStock));
}

return averages;
}

function getAveragePricesForStock(pricesForStock) {
let total = 0;

for(let price of pricesForStock) {
total += price;
}

return roundTo2Decimals(total / pricesForStock.length);
}

function roundTo2Decimals(num) {
return Math.round(num * 100) / 100;
}

/*
Expand All @@ -47,8 +80,27 @@ 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)
*/

/*
SOLUTION EXPLANATION: Again, as in the previous solution, we can divide a large problem into several smaller ones.
1. I created a new function that simply calculates the price change of ONE stock - getPriceChangeForStock.
2. This new function can also use the roundTo2Decimals function we used before.
One of the biggest benefits of using this feature is the ability to reuse code!
*/

function getPriceChanges(closingPricesForAllStocks) {
// TODO
let changes = [];

for(let pricesForStock of closingPricesForAllStocks) {
changes.push(getPriceChangeForStock(pricesForStock))
}

return changes;
}

function getPriceChangeForStock(pricesForStock) {
let priceChange = pricesForStock[pricesForStock.length - 1] - pricesForStock[0]
return roundTo2Decimals(priceChange);
}

/*
Expand All @@ -63,10 +115,55 @@ function getPriceChanges(closingPricesForAllStocks) {
The stock ticker should be capitalised.
The price should be shown with exactly 2 decimal places.
*/

/*
EXPLANATION : We can also break this problem down into smaller problems.
1. I created a new function that simply calculates the highest price for a single stock - getHighestPrice.
2. This new function can also use the roundTo2Decimals function
Here I have included an alternative solution that uses JavaScript's Math.max() function
The Math.max() function accepts zero or more numbers as input parameters.
We can convert our array into individual numbers, which can then be passed to this function using the propagation syntax: ...
*/

function highestPriceDescriptions(closingPricesForAllStocks, stocks) {
// TODO
let descriptions = [];

for(let i = 0; i < closingPricesForAllStocks.length; i++) {
let highestPrice = getHighestPrice(closingPricesForAllStocks[i]);
descriptions.push(`The highest price of ${stocks[i].toUpperCase()} in the last 5 days was ${highestPrice.toFixed(2)}`);
}

return descriptions;

}

function getHighestPrice(pricesForStock) {
//initialising to 0, as we are expecting this value to be overriden by the first price in the array
let highestPriceSoFar = 0;

for(let price of pricesForStock) {
//if this price is higher than the highestprice we are seen so far, it becomes the new highest price
if(price > highestPriceSoFar) {
highestPriceSoFar = price;
}
}

return highestPriceSoFar;
}

function highestPriceDescriptionsAllternate(closingPricesForAllStocks, stocks) {
let descriptions = [];

for(let i = 0; i < closingPricesForAllStocks.length; i++) {
let highestPrice = Math.max(...closingPricesForAllStocks[i]);
descriptions.push(`The highest price of ${stocks[i].toUpperCase()} in the last 5 days was ${highestPrice.toFixed(2)}`);
}

return descriptions;

}



/* ======= TESTS - DO NOT MODIFY ===== */
test("should return the average price for each stock", () => {
Expand Down