Skip to content
This repository was archived by the owner on Jan 14, 2024. It is now read-only.
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
18 changes: 18 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [

{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/../javascript/Javascript-Week1/week3-js"
}
]
}
15 changes: 10 additions & 5 deletions 1-exercises/A-undefined/exercise.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@
For each example, can you explain why we are seeing undefined?
*/

// Example 1
// Example 1 ->
//We haven't asigned a value to variable ' a ' and because of that we don't have a value to log yet
// that's why 'a' will show undefined
let a;
console.log(a);


// Example 2
// Example 2 _-> This function doesn't return anything that's why the ' hello' will be undefined
function sayHello() {
let message = "Hello";
}
Expand All @@ -23,14 +25,17 @@ let hello = sayHello();
console.log(hello);


// Example 3
// Example 3 ->
//The function does not provide an argument for the 'user' and when we call this function it will display 'Hello Undefined'
function sayHelloToUser(user) {
console.log(`Hello ${user}`);
}

sayHelloToUser();


// Example 4
let arr = [1,2,3];
// Example 4 ->
//Array counting starts from 0 on Javascript, and because there is no array with index 3 the console will display 'undefined'

let arr = [1, 2, 3];
console.log(arr[3]);
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
4 changes: 2 additions & 2 deletions 1-exercises/C-array-get-set/exercise.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
*/

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
}

/*
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

numbers.push(4);
numbers[0] = 1;
/*
DO NOT EDIT BELOW THIS LINE
--------------------------- */
Expand Down
18 changes: 14 additions & 4 deletions 2-mandatory/1-weather-report.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,26 @@
For example, "The temperature in London is 10 degrees"
- Hint: you can call the temperatureService function from your function
*/

function getTemperatureReport(cities) {
// TODO
const weather = [];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Great job on this one 😄


for (const city of cities) {
const temperature = temperatureService(city);
if (temperature !== undefined) {
const statement = `The temperature in ${city} is ${temperature} degrees`;
weather.push(statement);
}
}

return weather;
}
Comment on lines +16 to 25

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

spot on! very clear and concise code :)




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

function temperatureService(city) {
let temparatureMap = new Map();
let temparatureMap = new Map();

temparatureMap.set('London', 10);
temparatureMap.set('Paris', 12);
Expand All @@ -28,7 +38,7 @@ function temperatureService(city) {
temparatureMap.set('Mumbai', 29);
temparatureMap.set('São Paulo', 23);
temparatureMap.set('Lagos', 33);

return temparatureMap.get(city);
}

Expand Down
47 changes: 41 additions & 6 deletions 2-mandatory/2-financial-times.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,68 @@
Implement the function below, which will return a new array containing only article titles which will fit.
*/
function potentialHeadlines(allArticleTitles) {
// TODO
headlines = []; // we declare an empty array so when we get the headlines with length<=65 we push them here

for (article of allArticleTitles) { // we loop through all articles and check their length

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Small suggestion: it is usually a good idea to declare the variable in the for loop with let or const:
for (const article of allArticleTitles) {

if (article.length <= 65) {
headlines.push(article); //for every headline that passes the condition we push it to the empty array
}

}
return headlines; //then we return the array with the headlines that have <=65 words
}

/*
The editor of the FT likes short headlines with only a few words!
Implement the function below, which returns the title with the fewest words.
(you can assume words will always be seperated by a space)
(you can assume words will always be separated by a space)
*/
function titleWithFewestWords(allArticleTitles) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nice solution 👍

// TODO
fewestWordsTitle = ''; //we use an empty string since we haven't had yet any article to display
titleLengthNr = Infinity; //we can use any limit we want too but we want to make sure that the limit for the comparison it's not very small so it can fit all headlines available

headlines = potentialHeadlines(allArticleTitles) //we get the function above by saying that headlines is inside this function as mentioned
//console.log(headlines) i used console.log to see if my headlines was displaying or not

for (headline of headlines) { //we loop through each headline from headlines array
// console.log(headline)
titleLength = headline.split(' ').length; //we calculate te length by splitting each headline to words and not counting spaces .
//console.log(titleLength)

if (titleLength < titleLengthNr) { //and compare it with the value we first gave the variable
fewestWordsTitle = headline; //the title with the smallest amount of words is going to be displayed in the variable fewestWords
titleLengthNr = titleLength; /*since we didn't have a starting value we used infinity to compare the length but after we passed the length of
at least one headline we compare it then to that and then let the function know that are the same */
}
}
return fewestWordsTitle; //function is going to return the headline with the fewest words
}

/*
The editor of the FT has realised that headlines which have numbers in them get more clicks!
The editor of the FT has realized 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)
*/
function headlinesWithNumbers(allArticleTitles) {
// TODO
function withNumber(title) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I like that you've put the withNumber logic into its own function 👍
It might be worth defining the withNumber function outside of the headlinesWithNumbers function - so it can potentially be re-used. But not a big deal!

if (title.search('[0-9]') >= 0) {
return true;
} else {
return false;
}

}
return allArticleTitles.filter(withNumber); // shorter way explained by our buddy so i thought to implement it
}

/*
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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks perfect - nice work 😄

// TODO
let totalChars = allArticleTitles.reduce((total, headline) => total + headline.length, 0); // we use reduce() method to store total nr of characters in all headlines,starting value is set to 0
let averageChars = Math.round(totalChars / allArticleTitles.length);
return averageChars;
}


Expand Down
39 changes: 35 additions & 4 deletions 2-mandatory/3-stocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,31 @@ const CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS = [
Functions can help with this!
*/
function getAveragePrices(closingPricesForAllStocks) {
// TODO

let averagePrices = [];
for (prices of closingPricesForAllStocks) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Same comment as above about using let or const in the for loop.

sum = 0;
for (item of prices) { //we use for within for so we can access the arrays of the array
sum += parseFloat(item);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Might be worth double-checking - is item already a Number? If it is, we may not need parseFloat here.

/*we use parseFloat (but we can use Number too ) to convert each item/string of the arrays to numbers and then calculate the sum ,in the
beginning i used sum=(sum+item )but this is a shorter way */

}

sumAverage = parseFloat((sum / prices.length).toFixed(2));
/* we calculate the average price by dividing the number of elements of the arrays provided with the calculated sum and use toFixed(2)
to display up to 2 decimal places */

averagePrices.push(sumAverage); //and push the average sum of each array to the averagePrice or else as named above STOCKS

}

return averagePrices; // and here we return the array with the averagePrices for each company
}




/*
We also want to see what the change in price is from the first day to the last day for each stock.
Implement the below function, which
Expand All @@ -48,9 +70,15 @@ function getAveragePrices(closingPricesForAllStocks) {
The price change value should be rounded to 2 decimal places, and should be a number (not a string)
*/
function getPriceChanges(closingPricesForAllStocks) {
// TODO
return closingPricesForAllStocks.map(prices => { // we use the map method to intenerate each element of closingPricesForAllStock

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Very nice and short implementation 😄
Again, you might need the parseFloat on lines 74 and 75.

let firstPrice = parseFloat(prices[0]); //parseFloat to turn it to a floating point number
let lastPrice = parseFloat(prices[prices.length - 1]); //prices[prices.length - 1] returns the last element of the prices array
return parseFloat((lastPrice - firstPrice).toFixed(2));
});

}


/*
As part of a financial report, we want to see what the highest price was for each stock in the last 5 days.
Implement the below function, which
Expand All @@ -60,11 +88,14 @@ function getPriceChanges(closingPricesForAllStocks) {
- Returns an array of strings describing what the highest price was for each stock.
For example, the first element of the array should be: "The highest price of AAPL in the last 5 days was 180.33"
The test will check for this exact string.
The stock ticker should be capitalised.
The stock ticker should be capitalized.
The price should be shown with exactly 2 decimal places.
*/
function highestPriceDescriptions(closingPricesForAllStocks, stocks) {
// TODO
return stocks.map((ticker, index) => { //map method makes it shorter to intenerate through each element of stocks by corresponding the index with the ticker and generate a new array

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Great work on this one!

const highestPrice = closingPricesForAllStocks[index].reduce((max, price) => Math.max(max, price), 0); //reduce method finds the highest price by taking two parameters max and price max is initialized to 0 and price is the prices currently being processed
return `The highest price of ${ticker.toUpperCase()} in the last 5 days was ${highestPrice.toFixed(2)}`; // toUpperCase returns the stock in a capitalized format
});
}


Expand Down
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
Like learning a musical instrument, programming requires daily practise.

The exercises are split into three folders: `exercises`, `mandatory` and `extra`. All homework in the `exercise` and `mandatory` section **must** be completed for homework by the following lesson.
The exercises are split into three folders: `exercises`, `mandatory` and `extra`. All homework in the `exercise` and `mandatory` section **must** be completed for homework by the following lesson.

The `extra` folder contains exercises that you can complete to challenge yourself, but are not required for the following lesson.


## Solutions

The solutions for this coursework can be found here:
Expand All @@ -15,7 +14,7 @@ This is a **private** repository. Please request access from your Teachers, Budd

## Testing your work

- Each of the *.js files in the `1-exercises` folder can be run from the terminal using the `node` command with the path to the file. For example, `node 1-exercises/A-undefined/exercise.js` can be run from the root of the project.
- Each of the \*.js files in the `1-exercises` folder can be run from the terminal using the `node` command with the path to the file. For example, `node 1-exercises/A-undefined/exercise.js` can be run from the root of the project.
- To run the tests in the `2-mandatory` folder, run `npm run test` from the root of the project (after having run `npm install` once before).
- To run the tests in the `3-extra` folder, run `npm run extra-tests` from the root of the project (after having run `npm install` once before).

Expand Down