diff --git a/1-exercises/A-undefined/demo.js b/1-exercises/A-undefined/demo.js new file mode 100644 index 00000000..79be4cc5 --- /dev/null +++ b/1-exercises/A-undefined/demo.js @@ -0,0 +1,116 @@ +function double(n) { + return n * 2; +} +console.log(double(3)); +console.log(double(5)); + + +function doubleEachElement(arr) { + let newArr = []; + for(let element of arr) { + let newValue = double(element); + newArr.push(newValue); + } + return newArr; +} + + +function triple(n) { + return n * 3; +} +console.log(double(3)); +console.log(double(5)); + +function tripleEachElement(arr) { + let newArr = []; + for(let element of arr) { + let newValue = triple(element); + newArr.push(newValue); + } + return newArr; +} + + +function update(arr, func) { + let newArr = []; + for(let element of arr) { + let newValue = func(element); + newArr.push(newValue); + } + return newArr; +} +let arr =[2, 3, 4]; +let doublesValues = update(arr, double); +let tripleValues = update(arr, triple); +console.log(doublesValues); +console.log(tripleValues); + +function double(n) { + return n * 2; +} +update(arr, double); + +function hello(teamMember) { + console.log("Hello " + teamMember); +} +function notifyPeople(team) { + for(teamMember of team) { + hello(teamMember); + } +} + +notifyPeople(arr, hello) + + +function goodBye(teamMember) { + console.log('Goodbye ' + teamMember); +} + function notifyPeople(team, func ){ + for(teamMember of team) { + func(teamMember); + + } + } + +notifyPeople(arr, goodBye); + + +let shoppingList = ['bananas', 'milk', 'bread']; +shoppingList.forEach(value => { + console.log(`We need to buy ${value}`); +}); + +let data = [1, 2, 3, 4, 5]; +let newArr = data.map(value => value * 2); + + +console.log(newArr); +console.log(data); + + +let data1 = [1, 2, 3, 4, 5]; +let evenNumbers = data.filter(value => { + return value % 2 === 0}); +console.log(evenNumbers); +console.log(data1); + +let data2 = [1, 2, 3, 4, 5]; +let firstEvenNumber = data.find(value => value % 2 === 0); +console.log(firstEvenNumber); + +let data3 = [1, 2, 3, 4, 5]; +data + .filter(value => value % 2 === 0) + .map(value => value * 3) + .forEach(value => console.log(value)); + + + + let channels = ["bbc1", "BBC2", "ITV", "channel4", +"Channel5", "bbc3", "bbc4", "itv2", "ITV3", "itv4"]; +console.log(channels); + +channels.map(channel => channel.toUpperCase) +let newChannel = channels.map(item => item.toUpperCase()); +let itvChannel = newChannel.filter(item => item.includes('ITV')) +newChannel.forEach(item => console.log(item)); diff --git a/1-exercises/A-undefined/exercise.js b/1-exercises/A-undefined/exercise.js index 0acfc78d..f1806fc6 100644 --- a/1-exercises/A-undefined/exercise.js +++ b/1-exercises/A-undefined/exercise.js @@ -1,36 +1,192 @@ -/* - 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. +// /* +// 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. - But usually, when you see undefined - it means something has gone wrong! +// 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. - For each example, can you explain why we are seeing undefined? -*/ +// Below are 4 typical examples of when you would see undefined. +// For each example, can you explain why we are seeing undefined? +// */ -// Example 1 -let a; -console.log(a); +// // Example 1 +// let a; +// console.log(a); +// //does not have assigned value// -// Example 2 -function sayHello() { - let message = "Hello"; +// // Example 2 +// function sayHello() { +// let message = "Hello"; +// } + +// let hello = sayHello(); +// console.log(hello); +// //a value was not returned// + +// // Example 3 +// function sayHelloToUser(user) { +// console.log(`Hello ${user}`); +// } + +// sayHelloToUser(); +// //there is no any parameter when sayHelloToUser() is called// + +// // Example 4 +// let arr = [1,2,3]; +// console.log(arr[3]); +// //there is no value in arr[3]// + + + +// let i = 0; +// while (i < 3) { +// console.log(i); + // i++ +// } + +function sumTo(n) { + let sum = 0; + let i = 0; + while(i <= n) { + sum = sum + i; + i = i + 1; + } + return sum; + +} +console.log(sumTo(3)); + + +function showStocks(stocks){ + if(stocks.lengths === 0) { + console.log("Empty Portfolio"); + } else { + let i = 1; +while (i <= stocks.length) { + console.log(stocks[i - 1]); + i++; +} +} +} +let stocks = ["aapl","msft","amzn","googl", +"tsla"] +showStocks(stocks); + + +for(let i = 0; i < 3; i++) { + console.log(i); } -let hello = sayHello(); -console.log(hello); -// Example 3 -function sayHelloToUser(user) { - console.log(`Hello ${user}`); +function sumTo(n) { + let sum = 0; + for( let i = 0; i <= n; i = i + 1) { + sum = sum + i; + + } + return sum; + +} +function showStocks(stocks){ + if(stocks.lengths === 0) { + console.log("Empty Portfolio"); + } else { +for(let i = 0; i < stocks.length; i++) { + console.log(stocks[i]); + } +} +} +stocks = ["aapl","msft","amzn","googl", +"tsla"] +showStocks(stocks); + -sayHelloToUser(); +let colours = ["red", "green", "blue"]; + for(let i = 0; i < colours.length; i++) { + let colour = colours[i]; + console.log(colour); + } + + + let colors = ["red", "green", "blue"]; +for(let color of colors) { + console.log(color); +} -// Example 4 -let arr = [1,2,3]; -console.log(arr[3]); +let phrase = "CodeYourFuture"; +for(let letter of phrase) { + console.log(letter); +} + + +function calculatechanges(prices) { + let change = prices[prices.length - 1] - prices[0]; + return change.toFixed(2); +} +function changeInPrices(closingPrices){ + let changes = []; + + for(let pricesForOneStock of closingPrices) { + let change = calculatechanges(pricesForOneStock); + changes.push(change); +} +return changes; +} + +const closingPricesLast5Days = [ + [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 +]; +let result = changeInPrices(closingPricesLast5Days); +console.log(result); + + +let fruits = ["orange", "apple", "banana"]; +fruits.splice(1, 2, "pear"); +console.log(fruits); +console.log(fruits.length) + + + let todo = ["order dog food", "do the dishes"]; + todo.splice(1, 1, 'take out garbage'); + +console.log(fruits); + +console.log(["orange", "apple", "banana"].sort()); + + +let array = [1, 2, 3]; +let firstNewArr = array.concat(4, 5, 6); +let secondNewArr = array.concat([4, 5, 6]); +console.log(firstNewArr); +console.log(secondNewArr); +console.log(array); + + +let arr = [1, 2, 3, 4, 5]; +console.log(arr.slice(0, 3)); +console.log(arr.slice(3)); +console.log(arr.slice(1, -1)); +console.log(arr); + +let arra = [1, 3, 5]; +console.log(arra.includes(2)); +console.log(arra.includes(3)); + +let arry = ["orange", "apple", "banana"]; +console.log(arry.join()); +console.log(arry.join(' - ')); + +let names = ['khadija', 'tom']; +console.log(names.join()); + +function namesInArray(names) { + +} \ No newline at end of file diff --git a/1-exercises/B-while-loop/exercise.js b/1-exercises/B-while-loop/exercise.js index b459888f..def9e376 100644 --- a/1-exercises/B-while-loop/exercise.js +++ b/1-exercises/B-while-loop/exercise.js @@ -1,12 +1,20 @@ /* - 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 result = []; + let i = 0; + while (i < n ) { + result.push(i * 2); + i++; + } + console.log(result.join()); } 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..5270f8d4 100644 --- a/1-exercises/C-while-loop-with-array/exercise.js +++ b/1-exercises/C-while-loop-with-array/exercise.js @@ -17,7 +17,15 @@ const BIRTHDAYS = [ ]; function findFirstJulyBDay(birthdays) { - // TODO + let currentIndex = 0; +while (currentIndex < birthdays.length) { +if (birthdays[currentIndex].includes('July')) { + + return birthdays[currentIndex]; + + } + currentIndex++; } +} 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..4fa5cf3a 100644 --- a/1-exercises/D-do-while/exercise.js +++ b/1-exercises/D-do-while/exercise.js @@ -7,8 +7,18 @@ */ function evenNumbersSum(n) { - // TODO -} + let sum = 0; +let i = 0; + do{ + sum += (i * 2); + i++; + } while (i < n ); + + return sum; + + } + + console.log(evenNumbersSum(3)); // should output 6 console.log(evenNumbersSum(0)); // should output 0 diff --git a/1-exercises/E-for-loop/exercise1.js b/1-exercises/E-for-loop/exercise1.js index db5fac64..cd5e1347 100644 --- a/1-exercises/E-for-loop/exercise1.js +++ b/1-exercises/E-for-loop/exercise1.js @@ -3,12 +3,15 @@ Change the while loop below into a for loop. */ - - -// Change the below code to use a for loop instead of a while loop. let i = 0; -while(i < 26) { +while (i < 26) { console.log(String.fromCharCode(97 + i)); i++; } + +// Change the below code to use a for loop instead of a while loop. +for (let i = 0; i < 26; i++) { + console.log(String.fromCharCode(97 + i)); + +} // 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..0b373287 100644 --- a/1-exercises/E-for-loop/exercise2.js +++ b/1-exercises/E-for-loop/exercise2.js @@ -28,6 +28,10 @@ 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: @@ -36,4 +40,4 @@ Zadie Smith is 40 years old Jane Austen is 41 years old Bell Hooks is 63 years old Yukiko Motoya is 49 years old -*/ +*/ diff --git a/1-exercises/F-for-of-loop/exercise.js b/1-exercises/F-for-of-loop/exercise.js index 65585c6a..4eac410b 100644 --- a/1-exercises/F-for-of-loop/exercise.js +++ b/1-exercises/F-for-of-loop/exercise.js @@ -10,7 +10,13 @@ let tubeStations = [ "Oxford Street", "Tottenham Court Road" ]; - +for (let station of tubeStations) { + console.log(station) +} // TODO Use a for-of loop to capitalise and output each letter in the string seperately. let str = "codeyourfuture"; +for ( let s of str) { + console.log(s.toUpperCase()) + +} diff --git a/2-mandatory/1-weather-report.js b/2-mandatory/1-weather-report.js index dcc2bdb0..9a894474 100644 --- a/2-mandatory/1-weather-report.js +++ b/2-mandatory/1-weather-report.js @@ -12,7 +12,12 @@ */ function getTemperatureReport(cities) { - // TODO + let arr=[]; + for (let city of cities) { + arr.push(`The temperature in ${city} is ${temperatureService(city)} degrees`); + + } + return arr; } @@ -39,7 +44,7 @@ test("should return a temperature report for the user's cities", () => { "São Paulo" ] - expect(getTemperatureReport(usersCities)).toEqual([ + expect(getTemperatureReport(usersCities)). toEqual([ "The temperature in London is 10 degrees", "The temperature in Paris is 12 degrees", "The temperature in São Paulo is 23 degrees" diff --git a/2-mandatory/2-retrying-random-numbers.js b/2-mandatory/2-retrying-random-numbers.js index 10aab37d..6b314ac6 100644 --- a/2-mandatory/2-retrying-random-numbers.js +++ b/2-mandatory/2-retrying-random-numbers.js @@ -10,8 +10,14 @@ function generateRandomNumber() { } function getRandomNumberGreaterThan50() { - // TODO - implement using a do-while loop -} + let generatedNumber; + + do { + generatedNumber = generateRandomNumber(); + } while (generatedNumber <= 50); + return generatedNumber; + } +console.log(getRandomNumberGreaterThan50()); /* ======= TESTS - DO NOT MODIFY ===== */ diff --git a/2-mandatory/3-financial-times.js b/2-mandatory/3-financial-times.js index 2ce6fb73..2d9a2549 100644 --- a/2-mandatory/3-financial-times.js +++ b/2-mandatory/3-financial-times.js @@ -5,7 +5,13 @@ Implement the function below, which will return a new array containing only article titles which will fit. */ function potentialHeadlines(allArticleTitles) { - // TODO + let arr =[]; + for (let article of allArticleTitles){ + if (article.length <= 65){ + arr.push(article) + } + } + return arr; } /* @@ -14,16 +20,34 @@ function potentialHeadlines(allArticleTitles) { (you can assume words will always be seperated by a space) */ function titleWithFewestWords(allArticleTitles) { - // TODO + let arr = []; + for (let i = 0; i < allArticleTitles.length; i++) { + arr.push(allArticleTitles[i].split(" ").length); + } + return allArticleTitles[arr.indexOf(Math.min(...arr))]; } -/* - 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. +function numberOfWords(title) { + return title.split('').length; +} +/*let + on 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 ctain a number. (Hint: remember that you can also loop through the characters of a string if you need to) */ function headlinesWithNumbers(allArticleTitles) { // TODO + let arr= []; + for (let article of allArticleTitles){ + for (let char of article){ + if (char>="0" && char<="9"){ + arr.push (article); + break; + } + + } + } + return arr } /* @@ -32,6 +56,13 @@ function headlinesWithNumbers(allArticleTitles) { */ function averageNumberOfCharacters(allArticleTitles) { // TODO + let sum = 0; + for (let article of allArticleTitles){ + sum += article.length; + + } + + return Math.round(sum / allArticleTitles.length) } diff --git a/2-mandatory/4-stocks.js b/2-mandatory/4-stocks.js index 72d62f94..1bdd97ce 100644 --- a/2-mandatory/4-stocks.js +++ b/2-mandatory/4-stocks.js @@ -34,10 +34,20 @@ const CLOSING_PRICES_LAST_5_DAYS_FOR_ALL_STOCKS = [ Functions can help with this! */ function getAveragePrices(closingPricesForAllStocks) { - // TODO +let totalArray = []; +for (let stockClosingPrices of closingPricesForAllStocks) { + let stockTotal = 0; + for(let stockClosingPrice of stockClosingPrices) { + stockTotal = stockClosingPrice + stockTotal; + } + let stockAverage = stockTotal / stockClosingPrices.length; + totalArray.push(Number(stockAverage.toFixed(2))); +} +return totalArray; } -/* + + /* 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) @@ -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 differenceArray = []; + for(let item of closingPricesForAllStocks) { + let firstDayPrice = item[0]; + let lastDayPrice = item[item.length-1]; + let difference = lastDayPrice - firstDayPrice; + differenceArray.push(Number(difference.toFixed(2))); + } + return differenceArray; } /* @@ -64,9 +81,13 @@ function getPriceChanges(closingPricesForAllStocks) { The price should be shown with exactly 2 decimal places. */ function highestPriceDescriptions(closingPricesForAllStocks, stocks) { - // TODO -} + let arr=[]; + for (let i=0;i { diff --git a/3-extra/1-factorial.js b/3-extra/1-factorial.js index 31f8052c..0a3997aa 100644 --- a/3-extra/1-factorial.js +++ b/3-extra/1-factorial.js @@ -10,6 +10,13 @@ function factorial(input) { // TODO + let i = 1; + let multy = 1; + while(i <= input) { + multy *= i; + i++; + } + return multy; } /* ======= TESTS - DO NOT MODIFY ===== */ diff --git a/3-extra/2-array-of-objects.js b/3-extra/2-array-of-objects.js index ee57960f..98a5395d 100644 --- a/3-extra/2-array-of-objects.js +++ b/3-extra/2-array-of-objects.js @@ -12,7 +12,22 @@ function getHighestRatedInEachGenre(books) { // TODO + + let output = []; + + let genres = Array.from(new Set(books.map(element => element.genre))); + + for (let genre in genres) { + let result = books + .filter(element => element.genre === genres[genre]) + .reduce((pV, cV) => pV.rating < cV.rating ? cV : pV); + + output.push(result.title); + } + + return output; } + /* ======= Book data - DO NOT MODIFY ===== */ diff --git a/3-extra/3-fibonacci.js b/3-extra/3-fibonacci.js index 9ef9aec7..9537e227 100644 --- a/3-extra/3-fibonacci.js +++ b/3-extra/3-fibonacci.js @@ -15,6 +15,11 @@ function generateFibonacciSequence(n) { // TODO + let arr = [0, 1]; + for (let i = 0; i < n - 2; i++) { +arr.push (arr[i] + arr[i + 1]); + } + return arr; } /* ======= TESTS - DO NOT MODIFY ===== */