diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..244a1f51 --- /dev/null +++ b/.vscode/launch.json @@ -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": [ + "/**" + ], + "program": "${workspaceFolder}/../javascript/Javascript-Week1/week3-js" + } + ] +} \ No newline at end of file diff --git a/1-exercises/A-undefined/exercise.js b/1-exercises/A-undefined/exercise.js index 0acfc78d..7a5fbfc8 100644 --- a/1-exercises/A-undefined/exercise.js +++ b/1-exercises/A-undefined/exercise.js @@ -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"; } @@ -23,7 +25,8 @@ 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}`); } @@ -31,6 +34,8 @@ function sayHelloToUser(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]); diff --git a/1-exercises/B-array-literals/exercise.js b/1-exercises/B-array-literals/exercise.js index 51eba5cc..8eaa43d6 100644 --- a/1-exercises/B-array-literals/exercise.js +++ b/1-exercises/B-array-literals/exercise.js @@ -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 diff --git a/1-exercises/C-array-get-set/exercise.js b/1-exercises/C-array-get-set/exercise.js index 5ca911d5..6736a5ee 100644 --- a/1-exercises/C-array-get-set/exercise.js +++ b/1-exercises/C-array-get-set/exercise.js @@ -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 } /* diff --git a/1-exercises/C-array-get-set/exercises2.js b/1-exercises/C-array-get-set/exercises2.js index 6b6b007a..7baaf887 100644 --- a/1-exercises/C-array-get-set/exercises2.js +++ b/1-exercises/C-array-get-set/exercises2.js @@ -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 --------------------------- */ diff --git a/2-mandatory/1-weather-report.js b/2-mandatory/1-weather-report.js index dcc2bdb0..8aba62ef 100644 --- a/2-mandatory/1-weather-report.js +++ b/2-mandatory/1-weather-report.js @@ -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 = []; + + 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; } + /* ======= TESTS - DO NOT MODIFY ===== */ function temperatureService(city) { - let temparatureMap = new Map(); + let temparatureMap = new Map(); temparatureMap.set('London', 10); temparatureMap.set('Paris', 12); @@ -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); } diff --git a/2-mandatory/2-financial-times.js b/2-mandatory/2-financial-times.js index 2ce6fb73..d5010c57 100644 --- a/2-mandatory/2-financial-times.js +++ b/2-mandatory/2-financial-times.js @@ -5,25 +5,58 @@ 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 + 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) { - // 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) { + 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 } /* @@ -31,7 +64,9 @@ function headlinesWithNumbers(allArticleTitles) { Implement the function below to return this number - rounded to the nearest integer. */ function averageNumberOfCharacters(allArticleTitles) { - // 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; } diff --git a/2-mandatory/3-stocks.js b/2-mandatory/3-stocks.js index 72d62f94..79b3e12a 100644 --- a/2-mandatory/3-stocks.js +++ b/2-mandatory/3-stocks.js @@ -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) { + sum = 0; + for (item of prices) { //we use for within for so we can access the arrays of the array + sum += parseFloat(item); + /*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 @@ -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 + 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 @@ -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 + 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 + }); } diff --git a/README.md b/README.md index 1ca17aae..631a4341 100644 --- a/README.md +++ b/README.md @@ -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: @@ -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).