From 3055de5deb866f8a6837f742a54d810b0ad4bd95 Mon Sep 17 00:00:00 2001 From: Saliha Popal Date: Sun, 5 Mar 2023 12:46:30 +0000 Subject: [PATCH 1/3] Mandatory done! --- 1-exercises/A-undefined/exercise.js | 20 +++-- 1-exercises/B-array-literals/exercise.js | 7 +- 1-exercises/C-array-get-set/exercise.js | 4 +- 1-exercises/C-array-get-set/exercises2.js | 7 ++ 1-exercises/D-for-loop/exercise.js | 7 ++ .../E-while-loop-with-array/exercise.js | 11 ++- 2-mandatory/1-weather-report.js | 34 ++++---- 2-mandatory/2-financial-times.js | 82 +++++++++++++++---- 2-mandatory/3-stocks.js | 53 ++++++++++-- 9 files changed, 174 insertions(+), 51 deletions(-) diff --git a/1-exercises/A-undefined/exercise.js b/1-exercises/A-undefined/exercise.js index 0acfc78d..dae7bb51 100644 --- a/1-exercises/A-undefined/exercise.js +++ b/1-exercises/A-undefined/exercise.js @@ -10,17 +10,18 @@ */ // Example 1 -let a; +//let a; //. a does not have value +let a = "Hi" console.log(a); // Example 2 function sayHello() { - let message = "Hello"; -} + return "Hello"; +} ////. this function have to return to something. -let hello = sayHello(); -console.log(hello); +let result = sayHello(); +console.log(result); //// should assign a variable // Example 3 @@ -28,9 +29,14 @@ function sayHelloToUser(user) { console.log(`Hello ${user}`); } -sayHelloToUser(); +sayHelloToUser(); // hello is undefined and recalled with no parameter. +sayHello(Maria); // should recall a value of a variable // Example 4 let arr = [1,2,3]; -console.log(arr[3]); +arr[3] = 4; + +console.log(arr[3]);// the length of array is 2 because it starts from 0. +//By adding arr[3] = 4; console.log(arr[3]) === true + diff --git a/1-exercises/B-array-literals/exercise.js b/1-exercises/B-array-literals/exercise.js index 51eba5cc..1d81f6e4 100644 --- a/1-exercises/B-array-literals/exercise.js +++ b/1-exercises/B-array-literals/exercise.js @@ -4,8 +4,11 @@ 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..008fd288 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]; } function last(arr) { - return; // complete this statement + return arr[arr.length-1]; } /* diff --git a/1-exercises/C-array-get-set/exercises2.js b/1-exercises/C-array-get-set/exercises2.js index 6b6b007a..6a7e85f0 100644 --- a/1-exercises/C-array-get-set/exercises2.js +++ b/1-exercises/C-array-get-set/exercises2.js @@ -7,6 +7,13 @@ */ let numbers = [1, 2, 3]; // Don't change this array literal declaration +numbers; +numbers.length; +//numbers[3] = 4; or +numbers[numbers.length] = 4; +numbers[0] = 1; + +console.log(numbers.length); /* DO NOT EDIT BELOW THIS LINE diff --git a/1-exercises/D-for-loop/exercise.js b/1-exercises/D-for-loop/exercise.js index 081002b2..4e562144 100644 --- a/1-exercises/D-for-loop/exercise.js +++ b/1-exercises/D-for-loop/exercise.js @@ -28,6 +28,13 @@ 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/E-while-loop-with-array/exercise.js b/1-exercises/E-while-loop-with-array/exercise.js index d584cd75..d9907788 100644 --- a/1-exercises/E-while-loop-with-array/exercise.js +++ b/1-exercises/E-while-loop-with-array/exercise.js @@ -16,8 +16,15 @@ const BIRTHDAYS = [ "November 15th" ]; -function findFirstJulyBDay(birthdays) { - // TODO +function findFirstJulyBDay(BIRTHDAYS) { + let i = 0; + while(i < BIRTHDAYS.length){ + if(BIRTHDAYS[i].includes("July")){ + return BIRTHDAYS[i]; + } + i++; + } } + console.log(findFirstJulyBDay(BIRTHDAYS)); // should output "July 11th" diff --git a/2-mandatory/1-weather-report.js b/2-mandatory/1-weather-report.js index dcc2bdb0..eb6a862e 100644 --- a/2-mandatory/1-weather-report.js +++ b/2-mandatory/1-weather-report.js @@ -2,7 +2,7 @@ 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 temperature. Implement the function below: - take the array of cities as a parameter @@ -11,25 +11,29 @@ - Hint: you can call the temperatureService function from your function */ -function getTemperatureReport(cities) { - // TODO -} - + function getTemperatureReport(cities){ + const statement = []; + for(const city of cities){ + const temperature = temperatureService(city) + statement.push(`The temperature in ${city} is ${temperature} degrees`) + } + return statement; + } /* ======= TESTS - DO NOT MODIFY ===== */ function temperatureService(city) { - let temparatureMap = new Map(); - - temparatureMap.set('London', 10); - temparatureMap.set('Paris', 12); - temparatureMap.set('Barcelona', 17); - temparatureMap.set('Dubai', 27); - temparatureMap.set('Mumbai', 29); - temparatureMap.set('São Paulo', 23); - temparatureMap.set('Lagos', 33); + let temperatureMap = new Map(); + + temperatureMap.set('London', 10); + temperatureMap.set('Paris', 12); + temperatureMap.set('Barcelona', 17); + temperatureMap.set('Dubai', 27); + temperatureMap.set('Mumbai', 29); + temperatureMap.set('São Paulo', 23); + temperatureMap.set('Lagos', 33); - return temparatureMap.get(city); + return temperatureMap.get(city); } test("should return a temperature report for the user's cities", () => { diff --git a/2-mandatory/2-financial-times.js b/2-mandatory/2-financial-times.js index 2ce6fb73..48d71b7b 100644 --- a/2-mandatory/2-financial-times.js +++ b/2-mandatory/2-financial-times.js @@ -4,36 +4,90 @@ 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 -} + function potentialHeadlines(allArticleTitles) { + // Create an empty array to store the potential headlines + const potentialHeadlines = []; + + // Loop through each article title in the input array + for (let i = 0; i < allArticleTitles.length; i++) { + const articleTitle = allArticleTitles[i]; + + // Check if the title is 65 characters or less + if (articleTitle.length <= 65) { + // If it is, add it to the potential headlines array + potentialHeadlines.push(articleTitle); + } + } + + // Return the array of potential headlines + return potentialHeadlines; + } + /* 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 -} + + let fewestWords = allArticleTitles[0]; + + for (let i = 0; i < allArticleTitles.length; i++) { + if (fewestWords.length > allArticleTitles[i].length) { + fewestWords = allArticleTitles[i]; + } + } + + return fewestWords; + } + /* - 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 -} + const headlinesWithNumbers = []; + + for (let i = 0; i < allArticleTitles.length; i++) { + const articleTitle = allArticleTitles[i]; + + for (let j = 0; j < articleTitle.length; j++) { + const character = articleTitle.charAt(j); + + if (!isNaN(parseInt(character))) { + headlinesWithNumbers.push(articleTitle); + } + } + } + + return headlinesWithNumbers; + } + /* 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 totalChars = 0; + + for (let i = 0; i < allArticleTitles.length; i++) { + totalChars += allArticleTitles[i].length; + } + + const averageChars = Math.round(totalChars / allArticleTitles.length); + + return averageChars; + } + + + /* ======= List of Articles - DO NOT MODIFY ===== */ @@ -42,9 +96,9 @@ const ARTICLE_TITLES = [ "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", + "Labor 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", + "Chinese social media users blast Elan 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", @@ -55,7 +109,7 @@ const ARTICLE_TITLES = [ 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", + "Labor 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" ])); diff --git a/2-mandatory/3-stocks.js b/2-mandatory/3-stocks.js index 72d62f94..cadc36e9 100644 --- a/2-mandatory/3-stocks.js +++ b/2-mandatory/3-stocks.js @@ -1,7 +1,7 @@ /* THESE EXERCISES ARE QUITE HARD. JUST DO YOUR BEST, AND COME WITH QUESTIONS IF YOU GET STUCK :) - Imagine we a working for a finance company. Below we have: + Imagine we are 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) @@ -34,8 +34,24 @@ const CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS = [ Functions can help with this! */ function getAveragePrices(closingPricesForAllStocks) { - // TODO -} + const averages = []; + + for (let i = 0; i < closingPricesForAllStocks.length; i++) { + const prices = closingPricesForAllStocks[i]; + let total = 0; + + for (let j = 0; j < prices.length; j++) { + total += prices[j]; + } + + const average = total / prices.length; + const roundedAverage = parseFloat(average.toFixed(2)); + averages.push(roundedAverage); + } + + return averages; + } + /* We also want to see what the change in price is from the first day to the last day for each stock. @@ -48,9 +64,17 @@ 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 -} - + const priceChanges = []; + + for (let i = 0; i < closingPricesForAllStocks.length; i++) { + const stockPrices = closingPricesForAllStocks[i]; + const priceChange = stockPrices[stockPrices.length - 1] - stockPrices[0]; + priceChanges.push(Number(priceChange.toFixed(2))); + } + + return priceChanges; + } + /* 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,12 +84,23 @@ 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 -} + const descriptions = []; + + for (let i = 0; i < closingPricesForAllStocks.length; i++) { + const ticker = stocks[i].toUpperCase(); + const prices = closingPricesForAllStocks[i]; + const maxPrice = Math.max(...prices).toFixed(2); + const description = `The highest price of ${ticker} in the last 5 days was ${maxPrice}`; + descriptions.push(description); + } + + return descriptions; + } + /* ======= TESTS - DO NOT MODIFY ===== */ From 0ab8d0efbb2224f15a1977d8d972baa5a6da9c9d Mon Sep 17 00:00:00 2001 From: Saliha Popal Date: Mon, 6 Mar 2023 19:40:15 +0000 Subject: [PATCH 2/3] Extra done --- 3-extra/1-radio-stations.js | 25 +++++++++++++++++++++++++ 3-extra/2-array-of-objects.js | 28 ++++++++++++++++++++++++++-- 3-extra/3-fibonacci.js | 13 +++++++++++-- 3 files changed, 62 insertions(+), 4 deletions(-) diff --git a/3-extra/1-radio-stations.js b/3-extra/1-radio-stations.js index 577076e9..13a089ff 100644 --- a/3-extra/1-radio-stations.js +++ b/3-extra/1-radio-stations.js @@ -14,6 +14,14 @@ */ // `getAllFrequencies` goes here +function getAllFrequencies() { + const frequencies = []; + for (let i = 87; i <= 108; i++) { + frequencies.push(i); + } + return frequencies; +} + /** * Next, let's write a function that gives us only the frequencies that are radio stations. @@ -26,6 +34,23 @@ */ // `getStations` goes here + +function getStations() { + const allFrequencies = getAllFrequencies(); + const radioStations = []; + + for (let i = 0; i < allFrequencies.length; i++) { + const frequency = allFrequencies[i]; + if (isRadioStation(frequency)) { + radioStations.push(frequency); + } + } + + return radioStations; +} + + + /* * ======= TESTS - DO NOT MODIFY ======= * Note: You are not expected to understand everything below this comment! diff --git a/3-extra/2-array-of-objects.js b/3-extra/2-array-of-objects.js index ee57960f..248159de 100644 --- a/3-extra/2-array-of-objects.js +++ b/3-extra/2-array-of-objects.js @@ -11,8 +11,32 @@ */ function getHighestRatedInEachGenre(books) { - // TODO -} + // First, group the books by genre using an object + const booksByGenre = {}; + for (const book of books) { + if (!(book.genre in booksByGenre)) { + // we create an empty array for the book's genre which is not a property of `booksByGenre` + booksByGenre[book.genre] = []; + } + booksByGenre[book.genre].push(book); + } + + // Then, find the highest-rated book in each genre and add its title to an array + const highestRatedTitles = []; + for (const genre in booksByGenre) { + let highestRatedBook = null; + for (const book of booksByGenre[genre]) { + if (highestRatedBook === null || book.rating > highestRatedBook.rating) { + highestRatedBook = book; + } + } + highestRatedTitles.push(highestRatedBook.title); + } + + return highestRatedTitles; + } + + /* ======= Book data - DO NOT MODIFY ===== */ diff --git a/3-extra/3-fibonacci.js b/3-extra/3-fibonacci.js index 9ef9aec7..0c4afdbb 100644 --- a/3-extra/3-fibonacci.js +++ b/3-extra/3-fibonacci.js @@ -14,8 +14,17 @@ */ function generateFibonacciSequence(n) { - // TODO -} + const sequence = [0, 1]; + + for (let i = 2; i < n; i++) { + const previous1 = sequence[i - 1]; + const previous2 = sequence[i - 2]; + sequence.push(previous1 + previous2); + } + return sequence; + } + + /* ======= TESTS - DO NOT MODIFY ===== */ test("should return the first 10 numbers in the Fibonacci Sequence", () => { From 9d4e4c05ee4bf0248ab240607a4c6565e23d6289 Mon Sep 17 00:00:00 2001 From: Saliha Popal Date: Thu, 16 Mar 2023 10:13:24 +0000 Subject: [PATCH 3/3] Adding filter method --- 2-mandatory/2-financial-times.js | 113 +++++++++++++++++++++++-------- 1 file changed, 84 insertions(+), 29 deletions(-) diff --git a/2-mandatory/2-financial-times.js b/2-mandatory/2-financial-times.js index 48d71b7b..01f52d4b 100644 --- a/2-mandatory/2-financial-times.js +++ b/2-mandatory/2-financial-times.js @@ -5,42 +5,97 @@ Implement the function below, which will return a new array containing only article titles which will fit. */ - function potentialHeadlines(allArticleTitles) { - // Create an empty array to store the potential headlines - const potentialHeadlines = []; + // function potentialHeadlines(allArticleTitles) { + // // Create an empty array to store the potential headlines + // const potentialHeadlines = []; - // Loop through each article title in the input array - for (let i = 0; i < allArticleTitles.length; i++) { - const articleTitle = allArticleTitles[i]; + // // Loop through each article title in the input array + // for (let i = 0; i < allArticleTitles.length; i++) { + // const articleTitle = allArticleTitles[i]; - // Check if the title is 65 characters or less - if (articleTitle.length <= 65) { - // If it is, add it to the potential headlines array - potentialHeadlines.push(articleTitle); - } - } - - // Return the array of potential headlines - return potentialHeadlines; - } + // // Check if the title is 65 characters or less + // if (articleTitle.length <= 65) { + // // If it is, add it to the potential headlines array + // potentialHeadlines.push(articleTitle); + // } + // } -/* + // // Return the array of potential headlines + // return potentialHeadlines; + // } + + + // Using filter function with loops + + // function filterPotentialHeadlines(allArticleTitles){ + // let potentialHeadlines = []; + // for(let title of allArticleTitles){ + // if(title.length <= 65){ + // potentialHeadlines.push(title); + // } + // } + // return potentialHeadlines; + // } + + // const allArticleTitles = [ "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", + // "Labor 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 Elan 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",] + // console.log(filterPotentialHeadlines(allArticleTitles)); + + + // Using the filter function without loops + + + function isPotentialHeadline(articleTitle){ + return articleTitle.length <= 65; + } + + function filterPotentialHeadlines(articleTitles){ + // Here filter takes the function as a parameter + return articleTitles.filter(isPotentialHeadline); + } + + const articleTitles = [ "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", + "Labor 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 Elan 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",] + + console.log(filterPotentialHeadlines(articleTitles)); + + + + + +/* 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 separated by a space) */ -function titleWithFewestWords(allArticleTitles) { - - let fewestWords = allArticleTitles[0]; - - for (let i = 0; i < allArticleTitles.length; i++) { - if (fewestWords.length > allArticleTitles[i].length) { - fewestWords = allArticleTitles[i]; - } + function titleWithFewestWords(allArticleTitles) { + + let fewestWords = allArticleTitles[0]; + + for (let i = 0; i < allArticleTitles.length; i++) { + if (fewestWords.length > allArticleTitles[i].length) { + fewestWords = allArticleTitles[i]; } - - return fewestWords; } + + return fewestWords; +} /* @@ -107,7 +162,7 @@ const ARTICLE_TITLES = [ /* ======= TESTS - DO NOT MODIFY ===== */ test("should only return potential headlines", () => { - expect(new Set(potentialHeadlines(ARTICLE_TITLES))).toEqual(new Set([ + expect(new Set(filterPotentialHeadlines(ARTICLE_TITLES))).toEqual(new Set([ "British companies look to muscle in on US retail investing boom", "Labor to take firm step towards oblivion on New Year's Day", "Audit profession unattractive to new recruits, says PwC boss", @@ -116,7 +171,7 @@ test("should only return potential headlines", () => { }); test("should return an empty array for empty input", () => { - expect(potentialHeadlines([])).toEqual([]); + expect(filterPotentialHeadlines([])).toEqual([]); }); test("should return the title with the fewest words", () => {