From eac51db9a8f294aba9da5890e14d7b45a18063d7 Mon Sep 17 00:00:00 2001 From: hanakisu <105117072+hanakisu@users.noreply.github.com> Date: Fri, 19 Aug 2022 00:28:12 +0100 Subject: [PATCH] javascript core 3 --- 1-exercises/A-undefined/exercise.js | 8 ++- 1-exercises/B-while-loop/exercise.js | 19 +++++- .../C-while-loop-with-array/exercise.js | 21 +++++- 1-exercises/D-do-while/exercise.js | 11 +++ 1-exercises/E-for-loop/exercise1.js | 6 +- 1-exercises/E-for-loop/exercise2.js | 4 +- 1-exercises/F-for-of-loop/exercise.js | 9 ++- 2-mandatory/1-weather-report.js | 9 ++- 2-mandatory/2-retrying-random-numbers.js | 8 ++- 2-mandatory/3-financial-times.js | 68 ++++++++++++++++--- 2-mandatory/4-stocks.js | 64 +++++++++++++---- 3-extra/1-factorial.js | 8 ++- 12 files changed, 194 insertions(+), 41 deletions(-) diff --git a/1-exercises/A-undefined/exercise.js b/1-exercises/A-undefined/exercise.js index 0acfc78d..e3fe3140 100644 --- a/1-exercises/A-undefined/exercise.js +++ b/1-exercises/A-undefined/exercise.js @@ -1,8 +1,10 @@ /* - By now, you would have already seen "undefined", either in an error message or being output from your program. + By now, you would have already seen "undefined", + either in an error message or being output from your program. But what does it mean? undefined represents the absence of a value. - In some cases, undefined will be used by a programmer intentionally, and they will write code to handle it. + In some cases, undefined will be used by a programmer intentionally, + and they will write code to handle it. But usually, when you see undefined - it means something has gone wrong! Below are 4 typical examples of when you would see undefined. @@ -11,7 +13,7 @@ // Example 1 let a; -console.log(a); +console.log(a);// 'a' has already been declared // Example 2 diff --git a/1-exercises/B-while-loop/exercise.js b/1-exercises/B-while-loop/exercise.js index b459888f..37c4576f 100644 --- a/1-exercises/B-while-loop/exercise.js +++ b/1-exercises/B-while-loop/exercise.js @@ -1,13 +1,26 @@ /* - while loops can be useful when you want to execute some code as long as some condition is true. + while loops can be useful when you want to execute some code as long as some condition + is true. - Using a while loop, complete the function below so it logs (using console.log) the first n even numbers as a comma-seperated string. + Using a while loop, complete the function below so it logs (using console.log) + the first n even numbers as a comma-seperated string. The list of numbers should start with 0. n is being passed in as a parameter. */ function evenNumbers(n) { - // TODO + let startnum = []; + let i = 0; + while (n > startnum.length) { + if (i % 2 === 0) { + startnum.push(i); + } + i++; + } + + console.log(startnum); } + + evenNumbers(3); // should output 0,2,4 evenNumbers(0); // should output nothing diff --git a/1-exercises/C-while-loop-with-array/exercise.js b/1-exercises/C-while-loop-with-array/exercise.js index d584cd75..6592d891 100644 --- a/1-exercises/C-while-loop-with-array/exercise.js +++ b/1-exercises/C-while-loop-with-array/exercise.js @@ -1,7 +1,9 @@ /* Loops can be useful when working with arrays. - In the below example, imagine we've defined an array holding the birthdays of your closest friends. - Use a while loop to search through the array until you find the first birthday in July, then return that birthday from the function. + In the below example, imagine we've defined an array holding the birthdays of your + closest friends. + 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 = [ @@ -17,7 +19,20 @@ const BIRTHDAYS = [ ]; function findFirstJulyBDay(birthdays) { - // TODO + let i = 0; + while (i < birthdays.length) { + let months = birthdays[i].substr(0, 4); + if (months === "July") { + return birthdays[i]; + } + i++; + } + } + + + + + console.log(findFirstJulyBDay(BIRTHDAYS)); // should output "July 11th" diff --git a/1-exercises/D-do-while/exercise.js b/1-exercises/D-do-while/exercise.js index f10d0764..c408d045 100644 --- a/1-exercises/D-do-while/exercise.js +++ b/1-exercises/D-do-while/exercise.js @@ -8,6 +8,17 @@ function evenNumbersSum(n) { // TODO + let i = 0; + const evenNum = []; + do { + if (i % 2 === 0) { + evenNum.push(i); + } + i++ + } while (n > evenNum.length) + + let sum = evenNum.reduce((acc, curr) => acc + curr, 0); + return sum; } console.log(evenNumbersSum(3)); // should output 6 diff --git a/1-exercises/E-for-loop/exercise1.js b/1-exercises/E-for-loop/exercise1.js index db5fac64..74ada820 100644 --- a/1-exercises/E-for-loop/exercise1.js +++ b/1-exercises/E-for-loop/exercise1.js @@ -7,8 +7,10 @@ // Change the below code to use a for loop instead of a while loop. let i = 0; -while(i < 26) { +for (let i = 0; i < 26; i++) { console.log(String.fromCharCode(97 + i)); - i++; } +//while(i < 26) { + + // The output shouldn't change. diff --git a/1-exercises/E-for-loop/exercise2.js b/1-exercises/E-for-loop/exercise2.js index 081002b2..b42038c6 100644 --- a/1-exercises/E-for-loop/exercise2.js +++ b/1-exercises/E-for-loop/exercise2.js @@ -27,7 +27,9 @@ const AGES = [ ]; // TODO - Write for loop code here - +for (let i = 0; i < WRITERS.length; i++) { + console.log(`${WRITERS[i]} is ${AGES[i]} years old`) +} /* The output should look something like this: diff --git a/1-exercises/F-for-of-loop/exercise.js b/1-exercises/F-for-of-loop/exercise.js index 65585c6a..d262bf46 100644 --- a/1-exercises/F-for-of-loop/exercise.js +++ b/1-exercises/F-for-of-loop/exercise.js @@ -2,6 +2,7 @@ A for-of loop is a easy and way of looping through the elements of an array, string or any other "iterable object" (think sequence of elements). */ + // TODO Use a for-of loop to output each of the tube stations below. let tubeStations = [ "Aldgate", @@ -11,6 +12,12 @@ let tubeStations = [ "Tottenham Court Road" ]; - +for (let arr of tubeStations) { + console.log(arr); +} // TODO Use a for-of loop to capitalise and output each letter in the string seperately. + let str = "codeyourfuture"; +for (arr of str) { + console.log(arr.toUpperCase()) +} \ No newline at end of file diff --git a/2-mandatory/1-weather-report.js b/2-mandatory/1-weather-report.js index dcc2bdb0..7a6d80f7 100644 --- a/2-mandatory/1-weather-report.js +++ b/2-mandatory/1-weather-report.js @@ -2,7 +2,8 @@ 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. + 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 @@ -12,7 +13,11 @@ */ function getTemperatureReport(cities) { - // TODO + for (let i = 0; i < cities.length; i++) { + let temp = temperatureService(cities[i]) + cities[i] = "The temperature in " + cities[i] + " is " +temp + " degrees"; + } + return cities; } diff --git a/2-mandatory/2-retrying-random-numbers.js b/2-mandatory/2-retrying-random-numbers.js index 10aab37d..562b1dc4 100644 --- a/2-mandatory/2-retrying-random-numbers.js +++ b/2-mandatory/2-retrying-random-numbers.js @@ -1,5 +1,6 @@ /* - In the below example, we want to keep calling generateRandomNumber until we get a value that is > 50. + In the below example, we want to keep calling generateRandomNumber until we get + a value that is > 50. Implement this using a do-while loop. */ @@ -11,6 +12,11 @@ function generateRandomNumber() { function getRandomNumberGreaterThan50() { // TODO - implement using a do-while loop + let i = 0; + do { + i = generateRandomNumber(); + }while(i < 50) + return i; } /* ======= TESTS - DO NOT MODIFY ===== */ diff --git a/2-mandatory/3-financial-times.js b/2-mandatory/3-financial-times.js index 2ce6fb73..8329ca29 100644 --- a/2-mandatory/3-financial-times.js +++ b/2-mandatory/3-financial-times.js @@ -1,11 +1,20 @@ /* - Imagine you are working on the Financial Times web site! They have a list of article titles stored in an array. + Imagine you are working on the Financial Times web site! + They have a list of article titles stored in an array. - The home page of the web site has a headline section, which only has space for article titles which are 65 characters or less. - Implement the function below, which will return a new array containing only article titles which will fit. + The home page of the web site has a headline section, + which only has space for article titles which are 65 characters or less. + Implement the function below, + which will return a new array containing only article titles which will fit. */ function potentialHeadlines(allArticleTitles) { - // TODO + let result = []; + for (let i = 0; i < allArticleTitles.length; i++) { + if (allArticleTitles[i] <= 65) { + result.push(allArticleTitles[i]) + } + } + return result; } /* @@ -14,24 +23,61 @@ function potentialHeadlines(allArticleTitles) { (you can assume words will always be seperated by a space) */ function titleWithFewestWords(allArticleTitles) { - // TODO + let result = ""; + let spaceCount = 1000; + for (let i = 0; i < allArticleTitles.length; i++) { + var wordSpaceCount = (allArticleTitles[i].split(" ").length - 1); + console.log( allArticleTitles[i] + " has a space " + wordSpaceCount) + if (wordSpaceCount < spaceCount) { + spaceCount = wordSpaceCount; + result = allArticleTitles[i]; + } + } + return result; } /* - 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) + 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) */ function headlinesWithNumbers(allArticleTitles) { // TODO + let result = []; + for (let i = 0; i < allArticleTitles.length; i++) { + let innersentece = allArticleTitles[i] + for (let j = 0; j < innersentece.length; j++){ + let value = innersentece[j] + if (!isNaN(value) && value != " ") + { + result.push(innersentece) + break; + } + } + } + return result; } /* - 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. + 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 sum = 0 + if (allArticleTitles.length == 0) { + return 0 + } + for (let i = 0; i < allArticleTitles.length; i++) { + sum = sum + allArticleTitles[i].length; + } + let average = 0 + average = sum / allArticleTitles.length + return average.toFixed(0) } diff --git a/2-mandatory/4-stocks.js b/2-mandatory/4-stocks.js index 72d62f94..69352cc6 100644 --- a/2-mandatory/4-stocks.js +++ b/2-mandatory/4-stocks.js @@ -3,8 +3,10 @@ Imagine we a working for a finance company. Below we have: - an array of stock tickers - - an array of arrays containing the closing price for each stock in each of the last 5 days. - For example, CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS[2] contains the prices for the last 5 days for STOCKS[2] (which is amzn) + - an array of arrays containing the closing price for each stock in each of the + - last 5 days. + For example, CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS[2] contains the prices + for the last 5 days for STOCKS[2] (which is amzn) */ /* ======= Stock data - DO NOT MODIFY ===== */ @@ -21,50 +23,88 @@ const CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS = [ /* We want to understand what the average price over the last 5 days for each stock is. Implement the below function, which - - Takes this CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS array as input (remember, it's an array of arrays) + - Takes this CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS array as input + (remember, it's an array of arrays) - Returns an array containing the average price over the last 5 days for each stock. For example, the first element of the resulting array should contain Apple’s (aapl) average stock price for the last 5 days. The second element should be Microsoft's (msft) average price, and so on. - The average value should be rounded to 2 decimal places, and should be a number (not a string) + The average value should be rounded to 2 decimal places, and sh + ould be a number (not a string) - Hint 1: To calculate the average of a set of values, you can add them together and divide by the number of values. + Hint 1: To calculate the average of a set of values, you can add them together and + divide by the number of values. So the average of 5, 10 and 20 is (5 + 10 + 20) / 3 = 11.67 Hint 2: If the problem seems complex, try breaking it down into smaller problems. - Solve the smaller problems, and then build those solutions back up to solve the larger problem. + Solve the smaller problems, and then build those solutions back up + to solve the larger problem. Functions can help with this! */ function getAveragePrices(closingPricesForAllStocks) { // TODO + let result = [] + for (let i = 0; i < closingPricesForAllStocks.length; i++){ + let companyStock = closingPricesForAllStocks[i]; + let sum = 0; + for (let j = 0; j < companyStock.length; j++){ + sum = sum + companyStock[j]; + } + result[i] = (sum / companyStock.length).toFixed(2) + } + return result; } /* - We also want to see what the change in price is from the first day to the last day for each stock. + 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 - - Takes this CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS array as input (remember, it's an array of arrays) + - Takes this CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS array as + input (remember, it's an array of arrays) - Returns an array containing the price change over the last 5 days for each stock. For example, the first element of the resulting array should contain Apple’s (aapl) price change for the last 5 days. In this example it would be: (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) + The price change value should be rounded to 2 decimal places, + and should be a number (not a string) */ function getPriceChanges(closingPricesForAllStocks) { // TODO + let result = [] + for (let i = 0; i < closingPricesForAllStocks.length; i++) { + let companyStock = closingPricesForAllStocks[i]; + + let lastNumber = companyStock.length - 1 + result[i] = (companyStock[lastNumber] - companyStock[0]).toFixed(2) + } + return result; } /* - As part of a financial report, we want to see what the highest price was for each stock in the last 5 days. + 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 - Takes 2 parameters: - the CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS array as input (remember, it's an array of arrays) - the STOCKS array - 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" + 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 price should be shown with exactly 2 decimal places. */ function highestPriceDescriptions(closingPricesForAllStocks, stocks) { - // TODO + let result = [] + for (let i = 0; i < closingPricesForAllStocks.length; i++) { + let companyStock = closingPricesForAllStocks[i]; + let highestValue = companyStock[0]; + for (let j = 0; j < companyStock.length; j++) { + if (companyStock[j] > highestValue) { + highestValue = companyStock[j] + } + } + result[i] = "The highest price of " + stocks[i].toUpperCase() + " in the last 5 days was " + highestValue.toFixed(2) + } + return result; } diff --git a/3-extra/1-factorial.js b/3-extra/1-factorial.js index 31f8052c..6c384b34 100644 --- a/3-extra/1-factorial.js +++ b/3-extra/1-factorial.js @@ -1,14 +1,18 @@ /* - In maths, the factorial of an integer (written as n!) is the product of an integer, and all the integers below it (not including zero). + In maths, the factorial of an integer (written as n!) is the product of an integer, + and all the integers below it (not including zero). See: https://en.wikipedia.org/wiki/Factorial For example, 3! is 6 (because 3 * 2 * 1 = 6) 5! is 120 (because 5 * 4 * 3 * 2 * 1 = 120) - Using a loop, complete the function below so it returns the factorial of the number being passed in. + Using a loop, complete the function below so it returns the factorial of the + number being passed in. */ function factorial(input) { + + // TODO }