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
17 changes: 17 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
// 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": "pwa-node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\1-exercises\\C-while-loop-with-array\\exercise.js"
}
]
}
5 changes: 4 additions & 1 deletion 1-exercises/A-undefined/exercise.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// Example 1
let a;
console.log(a);

// a should have a value for not to be undefined.a doesn't have a value.

// Example 2
function sayHello() {
Expand All @@ -21,6 +21,7 @@ function sayHello() {

let hello = sayHello();
console.log(hello);
// sayHello function is not returning a value therefore variable hello has no value.This is why console.log returns undefined.


// Example 3
Expand All @@ -29,8 +30,10 @@ function sayHelloToUser(user) {
}

sayHelloToUser();
// In line 32 function call doesn't have any parameter.Therefore it returns undefined.


// Example 4
let arr = [1,2,3];
console.log(arr[3]);
// Array doesn't have an item in index 3 so console.log returns undefined.
12 changes: 10 additions & 2 deletions 1-exercises/B-while-loop/exercise.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,16 @@
*/

function evenNumbers(n) {
// TODO
}
let i = 0;
let count = 0;
while (count < n) {
if (i % 2 === 0){
console.log(i);
count++;
}
i++;
}
};

evenNumbers(3); // should output 0,2,4
evenNumbers(0); // should output nothing
Expand Down
9 changes: 7 additions & 2 deletions 1-exercises/C-while-loop-with-array/exercise.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
Use a while loop to search through the array until you find the first birthday in July, then return that birthday from the function.
*/

const BIRTHDAYS = [
const BIRTHDAYS= [
"January 7th",
"February 12th",
"April 3rd",
Expand All @@ -17,7 +17,12 @@ const BIRTHDAYS = [
];

function findFirstJulyBDay(birthdays) {
// TODO

for(let i = 0; i < birthdays.length; i++){
if (birthdays[i].includes("July")){
return birthdays[i];
}
}
}

console.log(findFirstJulyBDay(BIRTHDAYS)); // should output "July 11th"
12 changes: 11 additions & 1 deletion 1-exercises/D-do-while/exercise.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,17 @@
*/

function evenNumbersSum(n) {
// TODO
let i = 0;
let sum = 0;
let count = 0;
do {
if (i % 2 === 0){
sum = sum + i;
count++;
};
i++
} while (count < n);
return sum;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

well done, this was difficult. If you check the solutions you can see how you can do this with only sum and i variables

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks Ellie, I checked the solution and I changed my solution with sum and i variables.

}

console.log(evenNumbersSum(3)); // should output 6
Expand Down
4 changes: 4 additions & 0 deletions 1-exercises/E-for-loop/exercise1.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,8 @@ while(i < 26) {
console.log(String.fromCharCode(97 + i));
i++;
}

for(i = 0; i < 26; i++){
console.log(String.fromCharCode(97 + i));
}
// The output shouldn't change.
4 changes: 4 additions & 0 deletions 1-exercises/E-for-loop/exercise2.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,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`)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

great use of interpolation!

}


/*
The output should look something like this:
Expand Down
10 changes: 10 additions & 0 deletions 1-exercises/F-for-of-loop/exercise.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@ let tubeStations = [
"Tottenham Court Road"
];

for (let name of tubeStations) {
console.log(name);
}




// TODO Use a for-of loop to capitalise and output each letter in the string seperately.
let str = "codeyourfuture";

for (let letter of str) {
console.log(letter.toUpperCase());
}
14 changes: 13 additions & 1 deletion 2-mandatory/1-weather-report.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,22 @@
*/

function getTemperatureReport(cities) {
// TODO
let cityWithTemperature = [];
for (let i = 0; i < cities.length; i++) {
let currentCity = cities[i];
let currentCityTemperature = temperatureService(currentCity);
cityWithTemperature.push(
`The temperature in ${currentCity} is ${currentCityTemperature} degrees`

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

great job

);
}
return cityWithTemperature;
}






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

function temperatureService(city) {
Expand Down
7 changes: 7 additions & 0 deletions 2-mandatory/2-retrying-random-numbers.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ function generateRandomNumber() {
}

function getRandomNumberGreaterThan50() {
let i = 0;

do {
i = generateRandomNumber();
} while (i <= 50);

return i;
// TODO - implement using a do-while loop
}

Expand Down
96 changes: 67 additions & 29 deletions 2-mandatory/3-financial-times.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
Implement the function below, which will return a new array containing only article titles which will fit.
*/
function potentialHeadlines(allArticleTitles) {
// TODO
let titlesMoreThan65Char = allArticleTitles.filter(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

great use of filter. You can also do this with a loop but it's great you're practising array methods :)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks Ellie, I did it with for loop again.

(title) => title.length <= 65
);
return titlesMoreThan65Char;
}

/*
Expand All @@ -14,7 +17,22 @@ function potentialHeadlines(allArticleTitles) {
(you can assume words will always be seperated by a space)
*/
function titleWithFewestWords(allArticleTitles) {
// TODO
// let shortestTitleLength = Infinity;
// return allArticleTitles.reduce((acc, title) => {
// if (title.split("").length < shortestTitleLength) {
// shortestTitleLength = titleLengthInWords;
// return title;
// } else {
// return acc;
// }
// }, "");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Great job! Just one minor detail, it may be best to remove commented out code in order to find the relevant code faster and easier.

let shortestTitle = allArticleTitles[0];
for (let i = 1; i < allArticleTitles.length; i++) {
if (allArticleTitles[i].split("").length < shortestTitle.split("").length) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

the test for this passes because the title with the shortest number of words is also the title with the fewest characters.
Can you tell what needs to change in order to check which title has the fewest words? Hint: what's the difference between

allArticleTitles[i].split("").length

and

allArticleTitles[i].split(" ").length

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Hi Ellie, the first one takes all the characters of the array as one item, therefore the length of the array is equal to the number of the characters including spaces. The second one is taking all the words in the array as an item, therefore the number of the words is the length of the array. I changed mine to the second one.

shortestTitle = allArticleTitles[i];
}
}
return shortestTitle;
}

/*
Expand All @@ -23,59 +41,79 @@ function titleWithFewestWords(allArticleTitles) {
(Hint: remember that you can also loop through the characters of a string if you need to)
*/
function headlinesWithNumbers(allArticleTitles) {
// TODO
const titlesToReturn = [];
const numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];

allArticleTitles.forEach((title) => {
title.split("").forEach((character) => {
if (numbers.includes(character)) {
titlesToReturn.push(title);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

wow, well done for using string & array methods. You can also do this with for loops, but array methods are more commonly used, so this is excellent work

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks Ellie, we did this together with the TA in the homework club. I tried to do this with loops as a second solution.

});
});

return titlesToReturn;
}

/*
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 totalCharacterNumber = 0;
for (let i = 0; i < allArticleTitles.length; i++) {
totalCharacterNumber =
totalCharacterNumber + allArticleTitles[i].split("").length;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

remember you can use .length on a string too, so you don't need to split the string

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks Ellie, I removed split.

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



/* ======= List of Articles - DO NOT MODIFY ===== */
const ARTICLE_TITLES = [
"Streaming wars drive media groups to spend more than $100bn on new content",
"Amazon Prime Video India country head: streaming is driving a TV revolution",
"Aerospace chiefs prepare for bumpy ride in recovery of long-haul flights",
"British companies look to muscle in on US retail investing boom",
"Libor to take firm step towards oblivion on New Year's Day",
"Audit profession unattractive to new recruits, says PwC boss",
"Chinese social media users blast Elon Musk over near miss in space",
"Companies raise over $12tn in 'blockbuster' year for global capital markets",
"The three questions that dominate investment",
"Brussels urges Chile's incoming president to endorse EU trade deal",
"Streaming wars drive media groups to spend more than $100bn on new content",
"Amazon Prime Video India country head: streaming is driving a TV revolution",
"Aerospace chiefs prepare for bumpy ride in recovery of long-haul flights",
"British companies look to muscle in on US retail investing boom",
"Libor to take firm step towards oblivion on New Year's Day",
"Audit profession unattractive to new recruits, says PwC boss",
"Chinese social media users blast Elon Musk over near miss in space",
"Companies raise over $12tn in 'blockbuster' year for global capital markets",
"The three questions that dominate investment",
"Brussels urges Chile's incoming president to endorse EU trade deal",
];

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

test("should only return potential headlines", () => {
expect(new Set(potentialHeadlines(ARTICLE_TITLES))).toEqual(new Set([
"British companies look to muscle in on US retail investing boom",
"Libor to take firm step towards oblivion on New Year's Day",
"Audit profession unattractive to new recruits, says PwC boss",
"The three questions that dominate investment"
]));
expect(new Set(potentialHeadlines(ARTICLE_TITLES))).toEqual(
new Set([
"British companies look to muscle in on US retail investing boom",
"Libor to take firm step towards oblivion on New Year's Day",
"Audit profession unattractive to new recruits, says PwC boss",
"The three questions that dominate investment",
])
);
});

test("should return an empty array for empty input", () => {
expect(potentialHeadlines([])).toEqual([]);
expect(potentialHeadlines([])).toEqual([]);
});

test("should return the title with the fewest words", () => {
expect(titleWithFewestWords(ARTICLE_TITLES)).toEqual("The three questions that dominate investment");
expect(titleWithFewestWords(ARTICLE_TITLES)).toEqual(
"The three questions that dominate investment"
);
});

test("should only return headlines containing numbers", () => {
expect(new Set(headlinesWithNumbers(ARTICLE_TITLES))).toEqual(new Set([
"Streaming wars drive media groups to spend more than $100bn on new content",
"Companies raise over $12tn in 'blockbuster' year for global capital markets"
]));
expect(new Set(headlinesWithNumbers(ARTICLE_TITLES))).toEqual(
new Set([
"Streaming wars drive media groups to spend more than $100bn on new content",
"Companies raise over $12tn in 'blockbuster' year for global capital markets",
])
);
});

test("should return the average number of characters in a headline", () => {
expect(averageNumberOfCharacters(ARTICLE_TITLES)).toEqual(65);
expect(averageNumberOfCharacters(ARTICLE_TITLES)).toEqual(65);
});
30 changes: 27 additions & 3 deletions 2-mandatory/4-stocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,17 @@ const CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS = [
Functions can help with this!
*/
function getAveragePrices(closingPricesForAllStocks) {
// TODO

let salesAveragePrices = []
for(let i = 0; i <closingPricesForAllStocks.length; i++){
let eachCompanySalesTotal = 0;
for(let j = 0; j < closingPricesForAllStocks[i].length; j++){

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

well done! This was tough. When you look at the solutions, think about how you can break this down into smaller problems and functions

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks Ellie, I checked the solution document, you are right the solution is clear and easier to understand than mine.

eachCompanySalesTotal = eachCompanySalesTotal + closingPricesForAllStocks[i][j];
}
//salesAveragePrices.push((eachCompanySalesTotal / 5).toFixed(2));
salesAveragePrices[i] = Number((eachCompanySalesTotal / 5).toFixed(2));
}
return salesAveragePrices;
}

/*
Expand All @@ -48,7 +58,14 @@ 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
let priceChangesAllCompanies = [];
for( const prices of closingPricesForAllStocks ){
let firstSalePrice = prices[0];
let lastSalePrice = prices[prices.length-1]
let priceChange = lastSalePrice - firstSalePrice;
priceChangesAllCompanies.push(Number(priceChange.toFixed(2)));
}
return priceChangesAllCompanies;
}

/*
Expand All @@ -64,7 +81,14 @@ function getPriceChanges(closingPricesForAllStocks) {
The price should be shown with exactly 2 decimal places.
*/
function highestPriceDescriptions(closingPricesForAllStocks, stocks) {
// TODO
let highestPriceByCompany = [];
for( let i = 0; i < closingPricesForAllStocks.length; i++ ){
let highestPrice = Math.max(...closingPricesForAllStocks[i]).toFixed(2);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

wow well done for finding Math.max to make life easier :)

highestPriceByCompany.push(
`The highest price of ${stocks[i].toUpperCase()} in the last 5 days was ${highestPrice}`
);
}
return highestPriceByCompany;
}


Expand Down
13 changes: 12 additions & 1 deletion 3-extra/1-factorial.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,19 @@
*/

function factorial(input) {
// TODO
let total = 1;
if (input === 0 || input === 1)
return 1;

for (let i = 1; i <= input; i++){
total = total * i
}
return total;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nice!






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

Expand Down