From b022b9986ccb46d64cdb3da5cf0ceef7dacf9333 Mon Sep 17 00:00:00 2001 From: Doris-Siu Date: Sun, 18 Sep 2022 15:06:02 +0100 Subject: [PATCH 1/5] Complete exercises A-C --- 1-exercises/A-undefined/exercise.js | 8 ++++++++ 1-exercises/B-while-loop/exercise.js | 10 ++++++++++ 1-exercises/C-while-loop-with-array/exercise.js | 9 +++++++++ 3 files changed, 27 insertions(+) diff --git a/1-exercises/A-undefined/exercise.js b/1-exercises/A-undefined/exercise.js index 0acfc78d..4c653284 100644 --- a/1-exercises/A-undefined/exercise.js +++ b/1-exercises/A-undefined/exercise.js @@ -13,6 +13,8 @@ let a; console.log(a); +// We are seeing "undefined" for a here because even though we declared an "a" variable before but no value has been assigned to "a". + // Example 2 function sayHello() { @@ -22,6 +24,8 @@ function sayHello() { let hello = sayHello(); console.log(hello); +// We are seeing "undefined" here because there is no return value from hello which is a function. + // Example 3 function sayHelloToUser(user) { @@ -30,7 +34,11 @@ function sayHelloToUser(user) { sayHelloToUser(); +// We are seeing "undefined" here because no argument is being passed into the function sayHelloToUser(user). // Example 4 let arr = [1,2,3]; console.log(arr[3]); + +// We are seeing "undefined" here because there is no arr[3] in the array, the last item in the array is arr[2]. + diff --git a/1-exercises/B-while-loop/exercise.js b/1-exercises/B-while-loop/exercise.js index b459888f..9b328d2a 100644 --- a/1-exercises/B-while-loop/exercise.js +++ b/1-exercises/B-while-loop/exercise.js @@ -7,6 +7,16 @@ function evenNumbers(n) { // TODO +let counter = 0; +let arr = []; +let num = 0; +while (n>counter) { + arr[counter] = num; + num = num+2; + counter++; +} + +console.log (arr); } evenNumbers(3); // should output 0,2,4 diff --git a/1-exercises/C-while-loop-with-array/exercise.js b/1-exercises/C-while-loop-with-array/exercise.js index d584cd75..8f2e90da 100644 --- a/1-exercises/C-while-loop-with-array/exercise.js +++ b/1-exercises/C-while-loop-with-array/exercise.js @@ -18,6 +18,15 @@ const BIRTHDAYS = [ function findFirstJulyBDay(birthdays) { // TODO + let counter = 0; + while (birthdays[counter].includes("July") === false) { + counter++; + } + + return birthdays[counter]; + + + } console.log(findFirstJulyBDay(BIRTHDAYS)); // should output "July 11th" From 0c049b1429d6c31da26fbe43322f117674371318 Mon Sep 17 00:00:00 2001 From: Doris-Siu Date: Sun, 18 Sep 2022 16:44:39 +0100 Subject: [PATCH 2/5] Complete exercises D-F --- 1-exercises/D-do-while/exercise.js | 12 ++++++++++++ 1-exercises/E-for-loop/exercise1.js | 4 +--- 1-exercises/E-for-loop/exercise2.js | 4 ++++ 1-exercises/F-for-of-loop/exercise.js | 9 +++++++++ 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/1-exercises/D-do-while/exercise.js b/1-exercises/D-do-while/exercise.js index f10d0764..f3b03194 100644 --- a/1-exercises/D-do-while/exercise.js +++ b/1-exercises/D-do-while/exercise.js @@ -8,8 +8,20 @@ function evenNumbersSum(n) { // TODO + let sum = 0; + let num = 0; + let counter = 0; + do { + sum += num; + num += 2; + counter++; + + } while (counter Date: Sun, 18 Sep 2022 17:34:15 +0100 Subject: [PATCH 3/5] Complete mandatory 1-2 --- 2-mandatory/1-weather-report.js | 10 ++++++++++ 2-mandatory/2-retrying-random-numbers.js | 22 ++++++++++++++-------- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/2-mandatory/1-weather-report.js b/2-mandatory/1-weather-report.js index dcc2bdb0..a535c256 100644 --- a/2-mandatory/1-weather-report.js +++ b/2-mandatory/1-weather-report.js @@ -11,10 +11,20 @@ - Hint: you can call the temperatureService function from your function */ +cities1 = ['London', 'Paris','Barcelona','Dubai','Mumbai', 'São Paulo','Lagos']; + function getTemperatureReport(cities) { // TODO + let arr = []; + for (let item of cities) { + let temp = temperatureService(item); + arr.push (`The temperature in ${item} is ${temp} degrees`); + } + return arr; } +getTemperatureReport(cities1); + /* ======= TESTS - DO NOT MODIFY ===== */ diff --git a/2-mandatory/2-retrying-random-numbers.js b/2-mandatory/2-retrying-random-numbers.js index 10aab37d..ab491e9c 100644 --- a/2-mandatory/2-retrying-random-numbers.js +++ b/2-mandatory/2-retrying-random-numbers.js @@ -5,20 +5,26 @@ // This function shouldn't be changed function generateRandomNumber() { - console.log("Generating number..."); - return Math.round(Math.random() * 100); + console.log("Generating number..."); + return Math.round(Math.random() * 100); } function getRandomNumberGreaterThan50() { - // TODO - implement using a do-while loop + // TODO - implement using a do-while loop + let result = 0; + do { + result = generateRandomNumber(); + } while (result <= 50); + + return result; } /* ======= TESTS - DO NOT MODIFY ===== */ test("Returned value should always be greater than 50", () => { - expect(getRandomNumberGreaterThan50()).toBeGreaterThan(50); - expect(getRandomNumberGreaterThan50()).toBeGreaterThan(50); - expect(getRandomNumberGreaterThan50()).toBeGreaterThan(50); - expect(getRandomNumberGreaterThan50()).toBeGreaterThan(50); - expect(getRandomNumberGreaterThan50()).toBeGreaterThan(50); + expect(getRandomNumberGreaterThan50()).toBeGreaterThan(50); + expect(getRandomNumberGreaterThan50()).toBeGreaterThan(50); + expect(getRandomNumberGreaterThan50()).toBeGreaterThan(50); + expect(getRandomNumberGreaterThan50()).toBeGreaterThan(50); + expect(getRandomNumberGreaterThan50()).toBeGreaterThan(50); }); From 77725a0a09b96a53437ae1848184d46862af87d6 Mon Sep 17 00:00:00 2001 From: Doris-Siu Date: Sun, 18 Sep 2022 23:19:17 +0100 Subject: [PATCH 4/5] Complete mandatory 3-4 --- 2-mandatory/3-financial-times.js | 96 ++++++++++++++++++++++---------- 2-mandatory/4-stocks.js | 96 +++++++++++++++++++++++--------- package.json | 3 + 3 files changed, 141 insertions(+), 54 deletions(-) diff --git a/2-mandatory/3-financial-times.js b/2-mandatory/3-financial-times.js index 2ce6fb73..46053ee7 100644 --- a/2-mandatory/3-financial-times.js +++ b/2-mandatory/3-financial-times.js @@ -5,7 +5,17 @@ Implement the function below, which will return a new array containing only article titles which will fit. */ function potentialHeadlines(allArticleTitles) { - // TODO + let fitTitleArr = []; + if (allArticleTitles == null) { + return fitTitleArr; + } + for (let title of allArticleTitles) { + if (title.length <= 65) { + fitTitleArr.push(title); + } + } + return fitTitleArr; + // TODO } /* @@ -14,7 +24,15 @@ function potentialHeadlines(allArticleTitles) { (you can assume words will always be seperated by a space) */ function titleWithFewestWords(allArticleTitles) { - // TODO + let countArr = []; + for (let title of allArticleTitles) { + let titleArr = title.split(" "); + countArr.push(titleArr); + } + let result = countArr.sort((a, b) => a.length - b.length)[0]; + return result.join(" "); + + // TODO } /* @@ -23,7 +41,15 @@ function titleWithFewestWords(allArticleTitles) { (Hint: remember that you can also loop through the characters of a string if you need to) */ function headlinesWithNumbers(allArticleTitles) { - // TODO + // TODO + let numTitleArr = []; + let conditions = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]; + for (let title of allArticleTitles) { + if (conditions.some((el) => title.includes(el))) { + numTitleArr.push(title); + } + } + return numTitleArr; } /* @@ -31,51 +57,63 @@ function headlinesWithNumbers(allArticleTitles) { Implement the function below to return this number - rounded to the nearest integer. */ function averageNumberOfCharacters(allArticleTitles) { - // TODO + // TODO + let sum = 0; + let totalOfArticle = allArticleTitles.length; + for (let item of allArticleTitles) { + let strLength = item.length; + sum += strLength; + } + let average = sum / totalOfArticle; + return Math.round(average); } - - /* ======= 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); }); diff --git a/2-mandatory/4-stocks.js b/2-mandatory/4-stocks.js index 72d62f94..267844fc 100644 --- a/2-mandatory/4-stocks.js +++ b/2-mandatory/4-stocks.js @@ -11,11 +11,11 @@ const STOCKS = ["aapl", "msft", "amzn", "googl", "tsla"]; 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 + [179.19, 180.33, 176.28, 175.64, 172.99], // AAPL + [340.69, 342.45, 334.69, 333.2, 327.29], // MSFT + [3384.44, 3393.39, 3421.37, 3420.74, 3408.34], // AMZN + [2951.88, 2958.13, 2938.33, 2928.3, 2869.45], // GOOGL + [1101.30, 1093.94, 1067.0, 1008.87, 938.53], // TSLA ]; /* @@ -34,7 +34,18 @@ const CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS = [ Functions can help with this! */ function getAveragePrices(closingPricesForAllStocks) { - // TODO + // TODO + let averageOfStock = []; + let sum = 0; + for (let item of closingPricesForAllStocks) { + for (let element of item) { + sum += element; + } + let average = sum / 5; + averageOfStock.push(parseFloat(average.toFixed(2))); + sum = 0; + } + return averageOfStock; } /* @@ -48,7 +59,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 + // TODO + let priceChangeOfStock = []; + for (let item of closingPricesForAllStocks) { + let priceChange = item[4] - item[0]; + let formattedPriceChange = parseFloat(priceChange.toFixed(2)); + priceChangeOfStock.push(formattedPriceChange); + priceChange = 0; + } + return priceChangeOfStock; } /* @@ -64,31 +83,58 @@ function getPriceChanges(closingPricesForAllStocks) { The price should be shown with exactly 2 decimal places. */ function highestPriceDescriptions(closingPricesForAllStocks, stocks) { - // TODO -} + // TODO + let highestOfStock = []; + let stockName = []; + let describingArr = []; + + for (let item of closingPricesForAllStocks) { + let maxPrice = 0; + for (let price of item) { + if (price > maxPrice) { + maxPrice = price; + } + } + + highestOfStock.push(maxPrice.toFixed(2)); + //highestOfStock.push(Math.max.apply(null,item)); --> OK + // Math.max(array) --> not supported in the current version (will return NaN) + } + for (let element of stocks) { + stockName.push(element.toUpperCase()); + } + + for (let i = 0; i < 5; i++) { + let sentence = `The highest price of ${stockName[i]} in the last 5 days was ${highestOfStock[i]}`; + describingArr.push(sentence); + } + + return describingArr; +} -/* ======= TESTS - DO NOT MODIFY ===== */ +highestPriceDescriptions(CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS, STOCKS); +// /* ======= TESTS - DO NOT MODIFY ===== */ test("should return the average price for each stock", () => { - expect(getAveragePrices(CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS)).toEqual( - [176.89, 335.66, 3405.66, 2929.22, 1041.93] - ); + expect(getAveragePrices(CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS)).toEqual([ + 176.89, 335.66, 3405.66, 2929.22, 1041.93, + ]); }); test("should return the price change for each stock", () => { - expect(getPriceChanges(CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS)).toEqual( - [-6.2, -13.4, 23.9, -82.43, -162.77] - ); + expect(getPriceChanges(CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS)).toEqual([ + -6.2, -13.4, 23.9, -82.43, -162.77, + ]); }); test("should return a description of the highest price for each stock", () => { - expect(highestPriceDescriptions(CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS, STOCKS)).toEqual( - [ - "The highest price of AAPL in the last 5 days was 180.33", - "The highest price of MSFT in the last 5 days was 342.45", - "The highest price of AMZN in the last 5 days was 3421.37", - "The highest price of GOOGL in the last 5 days was 2958.13", - "The highest price of TSLA in the last 5 days was 1101.30" - ] - ); + expect( + highestPriceDescriptions(CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS, STOCKS) + ).toEqual([ + "The highest price of AAPL in the last 5 days was 180.33", + "The highest price of MSFT in the last 5 days was 342.45", + "The highest price of AMZN in the last 5 days was 3421.37", + "The highest price of GOOGL in the last 5 days was 2958.13", + "The highest price of TSLA in the last 5 days was 1101.30", + ]); }); diff --git a/package.json b/package.json index dc4e9ace..46d8acaa 100644 --- a/package.json +++ b/package.json @@ -23,5 +23,8 @@ "homepage": "https://github.com/CodeYourFuture/JavaScript-Core-1-Coursework-Week3#readme", "devDependencies": { "jest": "^26.6.3" + }, + "dependencies": { + "node": "^18.9.0" } } From 3a6293531a7731706efd6f33d8ae2fd304768e6c Mon Sep 17 00:00:00 2001 From: Doris-Siu Date: Mon, 19 Sep 2022 16:04:12 +0100 Subject: [PATCH 5/5] Complete the extra exercises --- 3-extra/1-factorial.js | 15 +++- 3-extra/2-array-of-objects.js | 147 ++++++++++++++++++++-------------- 3-extra/3-fibonacci.js | 13 ++- 3 files changed, 109 insertions(+), 66 deletions(-) diff --git a/3-extra/1-factorial.js b/3-extra/1-factorial.js index 31f8052c..f58acd06 100644 --- a/3-extra/1-factorial.js +++ b/3-extra/1-factorial.js @@ -9,19 +9,26 @@ */ function factorial(input) { - // TODO + // TODO + let counter = 1; + let product = 1; + while (counter <= input) { + product *= counter; + counter++; + } + return product; } /* ======= TESTS - DO NOT MODIFY ===== */ test("3! should be 6", () => { - expect(factorial(3)).toEqual(6); + expect(factorial(3)).toEqual(6); }); test("5! should be 120", () => { - expect(factorial(5)).toEqual(120); + expect(factorial(5)).toEqual(120); }); test("10! should be 3628800", () => { - expect(factorial(10)).toEqual(3628800); + expect(factorial(10)).toEqual(3628800); }); diff --git a/3-extra/2-array-of-objects.js b/3-extra/2-array-of-objects.js index ee57960f..3138d361 100644 --- a/3-extra/2-array-of-objects.js +++ b/3-extra/2-array-of-objects.js @@ -11,72 +11,97 @@ */ function getHighestRatedInEachGenre(books) { - // TODO -} + let resultBooks = {}; + let genres = []; + let result = []; + for (let i = 0; i < books.length; i++) { + let genre = books[i]["genre"]; + if (genres.indexOf(genre) < 0) { + genres.push(genre); + } + + if ( + !resultBooks[genre] || + !resultBooks[genre]["rating"] || + resultBooks[genre]["rating"] < books[i]["rating"] + ) { + resultBooks[genre] = books[i]; + } + } + for (let i = 0; i < genres.length; i++) { + result.push(resultBooks[genres[i]]["title"]); + } + + return result; + // TODO +} /* ======= Book data - DO NOT MODIFY ===== */ const BOOKS = [ - { - title: "The Lion, the Witch and the Wardrobe", - genre: "children", - rating: 4.7 - }, - { - title: "Sapiens: A Brief History of Humankind", - genre: "non-fiction", - rating: 4.7 - }, - { - title: "Nadiya's Fast Flavours", - genre: "cooking", - rating: 4.7 - }, - { - title: "Harry Potter and the Philosopher's Stone", - genre: "children", - rating: 4.8 - }, - { - title: "A Life on Our Planet", - genre: "non-fiction", - rating: 4.8 - }, - { - title: "Dishoom: The first ever cookbook from the much-loved Indian restaurant", - genre: "cooking", - rating: 4.85 - }, - { - title: "Gangsta Granny Strikes Again!", - genre: "children", - rating: 4.9 - }, - { - title: "Diary of a Wimpy Kid", - genre: "children", - rating: 4.6 - }, - { - title: "BOSH!: Simple recipes. Unbelievable results. All plants.", - genre: "cooking", - rating: 4.6 - }, - { - title: "The Book Your Dog Wishes You Would Read", - genre: "non-fiction", - rating: 4.85 - }, -] + { + title: "The Lion, the Witch and the Wardrobe", + genre: "children", + rating: 4.7, + }, + { + title: "Sapiens: A Brief History of Humankind", + genre: "non-fiction", + rating: 4.7, + }, + { + title: "Nadiya's Fast Flavours", + genre: "cooking", + rating: 4.7, + }, + { + title: "Harry Potter and the Philosopher's Stone", + genre: "children", + rating: 4.8, + }, + { + title: "A Life on Our Planet", + genre: "non-fiction", + rating: 4.8, + }, + { + title: + "Dishoom: The first ever cookbook from the much-loved Indian restaurant", + genre: "cooking", + rating: 4.85, + }, + { + title: "Gangsta Granny Strikes Again!", + genre: "children", + rating: 4.9, + }, + { + title: "Diary of a Wimpy Kid", + genre: "children", + rating: 4.6, + }, + { + title: "BOSH!: Simple recipes. Unbelievable results. All plants.", + genre: "cooking", + rating: 4.6, + }, + { + title: "The Book Your Dog Wishes You Would Read", + genre: "non-fiction", + rating: 4.85, + }, +]; + +console.log(getHighestRatedInEachGenre(BOOKS)); /* ======= TESTS - DO NOT MODIFY ===== */ test("should return the highest rated book in each genre", () => { - expect(new Set(getHighestRatedInEachGenre(BOOKS))).toEqual(new Set( - [ - "The Book Your Dog Wishes You Would Read", - "Gangsta Granny Strikes Again!", - "Dishoom: The first ever cookbook from the much-loved Indian restaurant" - ] - )); -}); \ No newline at end of file + expect(new Set(getHighestRatedInEachGenre(BOOKS))).toEqual( + new Set([ + "The Book Your Dog Wishes You Would Read", + "Gangsta Granny Strikes Again!", + "Dishoom: The first ever cookbook from the much-loved Indian restaurant", + ]) + ); +}); diff --git a/3-extra/3-fibonacci.js b/3-extra/3-fibonacci.js index 9ef9aec7..cefa58f1 100644 --- a/3-extra/3-fibonacci.js +++ b/3-extra/3-fibonacci.js @@ -14,7 +14,18 @@ */ function generateFibonacciSequence(n) { - // TODO + let resultArr = []; + for (i = 0; i