diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 696fd85..4cb5a22 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,10 +1,10 @@ # Your Details -Your Name: -Your City: -Your Slack Name: +Your Name: Osagie Okoedo +Your City: Birmingham +Your Slack Name: Osagie Okoedo # Homework Details -Module: -Week: +Module: JavaScript +Week: 1 diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..822e5d1 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,17 @@ +{ + // 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": "${file}" + } + ] +} \ No newline at end of file diff --git a/week-1/1-exercises/B-hello-world/exercise.js b/week-1/1-exercises/B-hello-world/exercise.js index b179ee9..e137398 100644 --- a/week-1/1-exercises/B-hello-world/exercise.js +++ b/week-1/1-exercises/B-hello-world/exercise.js @@ -1 +1,10 @@ -console.log("Hello world"); +/* console.log() with quotes, single or double, returns the message on the console*/ +console.log("Hello world. I just started learning JavaScript!"); +console.log('Hello world. I just started learning JavaScript!'); +console.log("Hello world. I just started learning JavaScript!"); + +/*Without the quote marks, I see an error message (SyntaxError: missing) */ +console.log(Hello world. I just started learning JavaScript!); + +/* with just a number and no quotes the output is the number */ +console.log(4); diff --git a/week-1/1-exercises/C-variables/exercise.js b/week-1/1-exercises/C-variables/exercise.js index a6bbb97..09f4cd5 100644 --- a/week-1/1-exercises/C-variables/exercise.js +++ b/week-1/1-exercises/C-variables/exercise.js @@ -1,3 +1,7 @@ -// Start by creating a variable `greeting` +/* * */ +let greeting = "Hello world"; + +console.log(greeting); +console.log(greeting); console.log(greeting); diff --git a/week-1/1-exercises/D-strings/exercise.js b/week-1/1-exercises/D-strings/exercise.js index 2cffa6a..2f52b2c 100644 --- a/week-1/1-exercises/D-strings/exercise.js +++ b/week-1/1-exercises/D-strings/exercise.js @@ -1,3 +1,5 @@ // Start by creating a variable `message` +let message = "This is a string"; console.log(message); +console.log(typeof message); diff --git a/week-1/1-exercises/E-strings-concatenation/exercise.js b/week-1/1-exercises/E-strings-concatenation/exercise.js index 2cffa6a..c5cba5c 100644 --- a/week-1/1-exercises/E-strings-concatenation/exercise.js +++ b/week-1/1-exercises/E-strings-concatenation/exercise.js @@ -1,3 +1,4 @@ // Start by creating a variable `message` - -console.log(message); +let greeting = "Hello, my name is "; +let name = "Osagie"; +console.log(greeting + name); diff --git a/week-1/1-exercises/F-strings-methods/README.md b/week-1/1-exercises/F-strings-methods/README.md index a284654..8743096 100644 --- a/week-1/1-exercises/F-strings-methods/README.md +++ b/week-1/1-exercises/F-strings-methods/README.md @@ -4,7 +4,11 @@ You can find out how many characters there are in a string by using the `length` var name = "Daniel"; var nameLength = name.length; -console.log(nameLength); // Logs 6 +console.log(nameLength); // Logs 6var message = "This is a string"; +// var messageType = typeof message; + +// console.log(message); +// console.log(messageType); ``` You can also get a modified version of a string by calling _string methods_. Let's try one: @@ -20,7 +24,7 @@ You can find out more about string properties and methods by searching for "Java ## Exercise 1 -* Log a message that includes the length of your name +- Log a message that includes the length of your name ## Expected result @@ -30,8 +34,8 @@ My name is Daniel and my name is 6 characters long ## Exercise 2 -* Log the same message using the variable, `name` provided -* Use the `.trim` method to remove the extra whitespace +- Log the same message using the variable, `name` provided +- Use the `.trim` method to remove the extra whitespace ## Expected result diff --git a/week-1/1-exercises/F-strings-methods/exercise.js b/week-1/1-exercises/F-strings-methods/exercise.js index 2cffa6a..cd21087 100644 --- a/week-1/1-exercises/F-strings-methods/exercise.js +++ b/week-1/1-exercises/F-strings-methods/exercise.js @@ -1,3 +1,21 @@ // Start by creating a variable `message` +// Ecercise 1 // +let name = "Osagie"; +let namelength = name.length; +let message = + "My name is " + name + " and my name is " + namelength + " characters long"; +console.log(message); + +// Exercise 2 // +// For this exercise, I made spaces before and after name// +let nameWithSpace = " Osagie "; +let nameTrimmed = nameWithSpace.trim(); +let namelength = nameWithSpace.length; +let message = + "My name is " + + nameTrimmed + + " and my name is " + + nameTrimmed.length + + " characters long"; console.log(message); diff --git a/week-1/1-exercises/F-strings-methods/exercise2.js b/week-1/1-exercises/F-strings-methods/exercise2.js index b4b4694..035ef53 100644 --- a/week-1/1-exercises/F-strings-methods/exercise2.js +++ b/week-1/1-exercises/F-strings-methods/exercise2.js @@ -1,3 +1,11 @@ +// Exercise 2 // const name = " Daniel "; - +let nameTrimmed = name.trim(); +let namelength = nameTrimmed.length; +let message = + "My name is " + + nameTrimmed + + " and my name is " + + nameTrimmed.length + + " characters long"; console.log(message); diff --git a/week-1/1-exercises/G-numbers/exercise.js b/week-1/1-exercises/G-numbers/exercise.js index 49e7bc0..7188bcd 100644 --- a/week-1/1-exercises/G-numbers/exercise.js +++ b/week-1/1-exercises/G-numbers/exercise.js @@ -1 +1,8 @@ -// Start by creating a variables `numberOfStudents` and `numberOfMentors` +let numberOfStudents = 15; +let numberOfMentors = 8; + +let totalOfStudentsAndMentors = numberOfStudents + numberOfMentors; +let message = "Total number of students and mentors: "; + +console.log(message + totalOfStudentsAndMentors); +console.log(`${message}${totalOfStudentsAndMentors}`); diff --git a/week-1/1-exercises/I-floats/exercise.js b/week-1/1-exercises/I-floats/exercise.js index a5bbcd8..ca1bc08 100644 --- a/week-1/1-exercises/I-floats/exercise.js +++ b/week-1/1-exercises/I-floats/exercise.js @@ -1,2 +1,20 @@ var numberOfStudents = 15; var numberOfMentors = 8; +let totalofStudentsAndMentors = numberOfStudents + numberOfMentors; + +let percentOfStudents = (numberOfStudents / totalofStudentsAndMentors) * 100; +let percentOfMentors = (numberOfMentors / totalofStudentsAndMentors) * 100; + +let approxPercent = Math.round(percentOfStudents); +let approxPer = Math.round(percentOfMentors); +let comment1 = "Percentage students:"; +let comment2 = "Percentage mentors:"; + +// console.log(percentOfStudents); +// console.log(percentOfMentors); + +// console.log(approxPercent); +// console.log(approxPer); + +console.log(`${comment1} ${approxPercent}%`); +console.log(`${comment2} ${approxPer}%`); diff --git a/week-1/1-exercises/J-functions/exercise.js b/week-1/1-exercises/J-functions/exercise.js index 0ae5850..6198c17 100644 --- a/week-1/1-exercises/J-functions/exercise.js +++ b/week-1/1-exercises/J-functions/exercise.js @@ -1,7 +1,11 @@ function halve(number) { - // complete the function here + return number / 2; // complete the function here } -var result = halve(12); +let output = halve(12); +let result = halve(50); +let value = halve(36); +console.log(output); console.log(result); +console.log(value); diff --git a/week-1/1-exercises/J-functions/exercise2.js b/week-1/1-exercises/J-functions/exercise2.js index 82ef5e7..0df95e2 100644 --- a/week-1/1-exercises/J-functions/exercise2.js +++ b/week-1/1-exercises/J-functions/exercise2.js @@ -1,7 +1,7 @@ function triple(number) { - // complete function here + return number * 3; } -var result = triple(12); +let result = triple(12); console.log(result); diff --git a/week-1/1-exercises/K-functions-parameters/exercise.js b/week-1/1-exercises/K-functions-parameters/exercise.js index 8d5db5e..ee11221 100644 --- a/week-1/1-exercises/K-functions-parameters/exercise.js +++ b/week-1/1-exercises/K-functions-parameters/exercise.js @@ -1,9 +1,7 @@ -// Complete the function so that it takes input parameters -function multiply() { - // Calculate the result of the function and return it -} - -// Assign the result of calling the function the variable `result` -var result = multiply(3, 4); +// multiplication function// +function multiply(a, b) { + return a * b; +} +let result = multiply(3, 4); console.log(result); diff --git a/week-1/1-exercises/K-functions-parameters/exercise2.js b/week-1/1-exercises/K-functions-parameters/exercise2.js index db7a890..e346262 100644 --- a/week-1/1-exercises/K-functions-parameters/exercise2.js +++ b/week-1/1-exercises/K-functions-parameters/exercise2.js @@ -1,5 +1,7 @@ // Declare your function first - -var result = divide(3, 4); +function divide(a, b) { + return a / b; +} +let result = divide(3, 4); console.log(result); diff --git a/week-1/1-exercises/K-functions-parameters/exercise3.js b/week-1/1-exercises/K-functions-parameters/exercise3.js index 537e9f4..abb24b6 100644 --- a/week-1/1-exercises/K-functions-parameters/exercise3.js +++ b/week-1/1-exercises/K-functions-parameters/exercise3.js @@ -1,5 +1,8 @@ // Write your function here - -var greeting = createGreeting("Daniel"); - -console.log(greeting); +function createGreeting(name) { + // let greeting = "Hello, my name is "; + // let fullGreeting = greeting + name; + let fullGreeting = "Hello, my name is " + name; + return fullGreeting; +} +console.log(createGreeting("Daniel")); diff --git a/week-1/1-exercises/K-functions-parameters/exercise4.js b/week-1/1-exercises/K-functions-parameters/exercise4.js index 7ab4458..85eacb2 100644 --- a/week-1/1-exercises/K-functions-parameters/exercise4.js +++ b/week-1/1-exercises/K-functions-parameters/exercise4.js @@ -1,5 +1,6 @@ // Declare your function first - +function sum(num1, num2) { + return num1 + num2; +} // Call the function and assign to a variable `sum` - -console.log(sum); +console.log(sum(13, 124)); // calling the function and passing the numbers diff --git a/week-1/1-exercises/K-functions-parameters/exercise5.js b/week-1/1-exercises/K-functions-parameters/exercise5.js index 7c5bcd6..7b10de8 100644 --- a/week-1/1-exercises/K-functions-parameters/exercise5.js +++ b/week-1/1-exercises/K-functions-parameters/exercise5.js @@ -1,5 +1,8 @@ // Declare your function here - -const greeting = createLongGreeting("Daniel", 30); - -console.log(greeting); +function createLongGreeting(name, age) { + // let name = "Daniel"; + // let age = 30; + const greeting = `My name is ${name} and I'm ${age} years old`; + return greeting; +} +console.log(createLongGreeting("Daniel", 30)); diff --git a/week-1/1-exercises/L-functions-nested/exercise.js b/week-1/1-exercises/L-functions-nested/exercise.js index a5d3774..89adaa1 100644 --- a/week-1/1-exercises/L-functions-nested/exercise.js +++ b/week-1/1-exercises/L-functions-nested/exercise.js @@ -1,5 +1,47 @@ +//Exercise 1// +function percentProgram(firstNumber, secondNumber) { + let overallTotal = firstNumber + secondNumber; + + let percentage = Math.round((firstNumber / overallTotal) * 100); + return percentage; +} + +function message(numberOfStudents, numberOfMentors) { + let percentOfStudents = percentProgram(numberOfStudents, numberOfMentors); + let percentOfMentors = percentProgram(numberOfMentors, numberOfStudents); + let fullMessage = `Percentage students: ${percentOfStudents}% Percentage mentors: ${percentOfMentors}%`; + return fullMessage; +} +let finalMessage = message(15, 8); +console.log(finalMessage); + +// console.log(`${comment1} ${approxPercent}%`); +// console.log(`${comment2} ${approxPer}%`); + var mentor1 = "Daniel"; var mentor2 = "Irina"; var mentor3 = "Mimi"; var mentor4 = "Rob"; var mentor5 = "Yohannes"; + +function shoutyGreeting(mentor) { + let nameUpperCase = mentor.toUpperCase(); + let greeting = `HELLO ${nameUpperCase}`; + return greeting; +} + +let greeting1 = shoutyGreeting(mentor1); +let greeting2 = shoutyGreeting(mentor2); +let greeting3 = shoutyGreeting(mentor3); +let greeting4 = shoutyGreeting(mentor4); +let greeting5 = shoutyGreeting(mentor5); + +console.log(greeting1); + +console.log(greeting2); + +console.log(greeting3); + +console.log(greeting4); + +console.log(greeting5); diff --git a/week-1/2-mandatory/1-syntax-errors.js b/week-1/2-mandatory/1-syntax-errors.js index fb756b6..31bb672 100644 --- a/week-1/2-mandatory/1-syntax-errors.js +++ b/week-1/2-mandatory/1-syntax-errors.js @@ -1,17 +1,16 @@ // There are syntax errors in this code - can you fix it to pass the tests? -function addNumbers(a b c) { - return a + b + c; +function addNumbers(a, b, c) { + return a + b + c; } -function introduceMe(name, age) -return "Hello, my name is " + name "and I am " age + "years old"; +function introduceMe(name, age) { + return "Hello, my name is " + name + " and I am " + age + " years old"; +} function getTotal(a, b) { - total = a ++ b; - - // Use string interpolation here - return "The total is %{total}" + let total = a + b; + return `The total is ${total}`; } /* ======= TESTS - DO NOT MODIFY ===== @@ -20,19 +19,25 @@ There are some Tests in this file that will help you work out if your code is wo To run these tests type `node 1-syntax-errors.js` into your terminal */ -const util = require('util'); +const util = require("util"); function test(test_name, actual, expected) { - let status; - if (actual === expected) { - status = "PASSED"; - } else { - status = `FAILED: expected: ${util.inspect(expected)} but your function returned: ${util.inspect(actual)}`; - } - - console.log(`${test_name}: ${status}`); + let status; + if (actual === expected) { + status = "PASSED"; + } else { + status = `FAILED: expected: ${util.inspect( + expected + )} but your function returned: ${util.inspect(actual)}`; + } + + console.log(`${test_name}: ${status}`); } test("fixed addNumbers function - case 1", addNumbers(3, 4, 6), 13); -test("fixed introduceMe function", introduceMe("Sonjide", 27), "Hello, my name is Sonjide and I am 27 years old"); +test( + "fixed introduceMe function", + introduceMe("Sonjide", 27), + "Hello, my name is Sonjide and I am 27 years old" +); test("fixed getTotal function", getTotal(23, 5), "The total is 28"); diff --git a/week-1/2-mandatory/2-logic-error.js b/week-1/2-mandatory/2-logic-error.js index c844460..ef7daf3 100644 --- a/week-1/2-mandatory/2-logic-error.js +++ b/week-1/2-mandatory/2-logic-error.js @@ -1,16 +1,15 @@ // The syntax for this function is valid but it has an error, find it and fix it. function trimWord(word) { - return wordtrim(); + return word.trim(); } function getWordLength(word) { - return "word".length() + return word.length; } function multiply(a, b, c) { - a * b * c; - return; + return a * b * c; } /* ======= TESTS - DO NOT MODIFY ===== @@ -19,6 +18,28 @@ There are some Tests in this file that will help you work out if your code is wo To run these tests type `node 2-logic-error` into your terminal */ +<<<<<<< HEAD +function test(test_name, expr) { + let status; + if (expr) { + status = "PASSED"; + } else { + status = "FAILED"; + } + + console.log(`${test_name}: ${status}`); +} + +test( + "fixed trimWord function", + trimWord(" CodeYourFuture ") === "CodeYourFuture" +); +test( + "fixed wordLength function", + getWordLength("A wild sentence appeared!") === 25 +); +test("fixed multiply function", multiply(2, 3, 6) === 36); +======= const util = require('util'); function test(test_name, actual, expected) { @@ -35,3 +56,4 @@ function test(test_name, actual, expected) { test("fixed trimWord function", trimWord(" CodeYourFuture "), "CodeYourFuture"); test("fixed wordLength function", getWordLength("A wild sentence appeared!"), 25); test("fixed multiply function", multiply(2, 3, 6), 36); +>>>>>>> 8d17c19782cb831f7eeeb6c2adc0555b17d81af4 diff --git a/week-1/2-mandatory/3-function-output.js b/week-1/2-mandatory/3-function-output.js index c8e8577..ec196d2 100644 --- a/week-1/2-mandatory/3-function-output.js +++ b/week-1/2-mandatory/3-function-output.js @@ -1,16 +1,19 @@ // Add comments to explain what this function does. You're meant to use Google! -function getNumber() { - return Math.random() * 10; -} +function letterSet() { + return Math.random() * 10; //Math.random() syntax is a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). +} //This will return random numbers between 0 to 9: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. // Add comments to explain what this function does. You're meant to use Google! -function s(w1, w2) { - return w1.concat(w2); +function words(w1, w2, w3) { + return str.concat(w1, w2, w3); // The concat() method is used to join two or more strings. } +/*Option 2: return w1.concat(w2, w3);*/ function concatenate(firstWord, secondWord, thirdWord) { - // Write the body of this function to concatenate three words together. - // Look at the test case below to understand what this function is expected to return. + // Write the body of this function to concatenate three words together + // Look at the test case below to understand what to expect in return + + return `${firstWord} ${secondWord} ${thirdWord}`; } /* ======= TESTS - DO NOT MODIFY ===== @@ -18,31 +21,33 @@ There are some Tests in this file that will help you work out if your code is wo To run these tests type `node 3-function-output` into your terminal */ -const util = require('util'); +const util = require("util"); function test(test_name, actual, expected) { - let status; - if (actual === expected) { - status = "PASSED"; - } else { - status = `FAILED: expected: ${util.inspect(expected)} but your function returned: ${util.inspect(actual)}`; - } - - console.log(`${test_name}: ${status}`); + let status; + if (actual === expected) { + status = "PASSED"; + } else { + status = `FAILED: expected: ${util.inspect( + expected + )} but your function returned: ${util.inspect(actual)}`; + } + + console.log(`${test_name}: ${status}`); } test( "concatenate function - case 1 works", - concatenate('code', 'your', 'future'), + concatenate("code", "your", "future"), "code your future" ); test( "concatenate function - case 2 works", - concatenate('I', 'like', 'pizza'), + concatenate("I", "like", "pizza"), "I like pizza" ); test( "concatenate function - case 3 works", - concatenate('I', 'am', 13), + concatenate("I", "am", 13), "I am 13" ); diff --git a/week-1/2-mandatory/4-tax.js b/week-1/2-mandatory/4-tax.js index 79db540..55137bd 100644 --- a/week-1/2-mandatory/4-tax.js +++ b/week-1/2-mandatory/4-tax.js @@ -5,7 +5,14 @@ Sales tax is 20% of the price of the product */ -function calculateSalesTax() {} +/* productPrice is the price before tax*/ +/* salesTaxPercentage is 20% equivalent to 0.20*/ + +function calculateSalesTax(productPrice) { + let salesTaxPercentage = 0.2; + return productPrice + productPrice * salesTaxPercentage; +} +/* function returns salesPrice after tax is added*/ /* CURRENCY FORMATTING @@ -17,30 +24,47 @@ function calculateSalesTax() {} Remember that the prices must include the sales tax (hint: you already wrote a function for this!) */ -function addTaxAndFormatCurrency() {} +function addTaxAndFormatCurrency(productPrice) { + let formattedValue = `£${calculateSalesTax(productPrice).toFixed(2)}`; + return formattedValue; +} /* ======= TESTS - DO NOT MODIFY ===== There are some Tests in this file that will help you work out if your code is working. To run these tests type `node 4-tax.js` into your terminal */ -const util = require('util'); +const util = require("util"); function test(test_name, actual, expected) { - let status; - if (actual === expected) { - status = "PASSED"; - } else { - status = `FAILED: expected: ${util.inspect(expected)} but your function returned: ${util.inspect(actual)}`; - } - - console.log(`${test_name}: ${status}`); + let status; + if (actual === expected) { + status = "PASSED"; + } else { + status = `FAILED: expected: ${util.inspect( + expected + )} but your function returned: ${util.inspect(actual)}`; + } + + console.log(`${test_name}: ${status}`); } -test("calculateSalesTax function - case 1 works", calculateSalesTax(15), 18) -test("calculateSalesTax function - case 2 works", calculateSalesTax(17.5), 21) -test("calculateSalesTax function - case 3 works", calculateSalesTax(34), 40.8) +test("calculateSalesTax function - case 1 works", calculateSalesTax(15), 18); +test("calculateSalesTax function - case 2 works", calculateSalesTax(17.5), 21); +test("calculateSalesTax function - case 3 works", calculateSalesTax(34), 40.8); -test("addTaxAndFormatCurrency function - case 1 works", addTaxAndFormatCurrency(15), "£18.00") -test("addTaxAndFormatCurrency function - case 2 works", addTaxAndFormatCurrency(17.5), "£21.00") -test("addTaxAndFormatCurrency function - case 3 works", addTaxAndFormatCurrency(34), "£40.80") +test( + "addTaxAndFormatCurrency function - case 1 works", + addTaxAndFormatCurrency(15), + "£18.00" +); +test( + "addTaxAndFormatCurrency function - case 2 works", + addTaxAndFormatCurrency(17.5), + "£21.00" +); +test( + "addTaxAndFormatCurrency function - case 3 works", + addTaxAndFormatCurrency(34), + "£40.80" +); diff --git a/week-1/3-extra/1-currency-conversion.js b/week-1/3-extra/1-currency-conversion.js index 5f06097..0730787 100644 --- a/week-1/3-extra/1-currency-conversion.js +++ b/week-1/3-extra/1-currency-conversion.js @@ -5,7 +5,9 @@ Write a function that converts a price to USD (exchange rate is 1.4 $ to £) */ -function convertToUSD() {} +function convertToUSD(pound) { + return pound * 1.4; +} /* CURRENCY FORMATTING @@ -15,7 +17,11 @@ function convertToUSD() {} They have also decided that they should add a 1% fee to all foreign transactions, which means you only convert 99% of the £ to BRL. */ -function convertToBRL() {} +function convertToBRL(pound) { + let convert = pound * 5.7; + let interest = convert * 0.01; + return convert - interest; +} /* ======= TESTS - DO NOT MODIFY ===== There are some Tests in this file that will help you work out if your code is working. @@ -23,17 +29,19 @@ There are some Tests in this file that will help you work out if your code is wo To run these tests type `node 1-currency-conversion` into your terminal */ -const util = require('util'); +const util = require("util"); function test(test_name, actual, expected) { - let status; - if (actual === expected) { - status = "PASSED"; - } else { - status = `FAILED: expected: ${util.inspect(expected)} but your function returned: ${util.inspect(actual)}`; - } - - console.log(`${test_name}: ${status}`); + let status; + if (actual === expected) { + status = "PASSED"; + } else { + status = `FAILED: expected: ${util.inspect( + expected + )} but your function returned: ${util.inspect(actual)}`; + } + + console.log(`${test_name}: ${status}`); } test("convertToUSD function works", convertToUSD(32), 44.8); diff --git a/week-1/3-extra/2-piping.js b/week-1/3-extra/2-piping.js index 067dd0f..5a38b8b 100644 --- a/week-1/3-extra/2-piping.js +++ b/week-1/3-extra/2-piping.js @@ -16,26 +16,28 @@ the final result to the variable goodCode */ -function add() { - +function add(pipe1, pipe2) { + return pipe1 + pipe2; } -function multiply() { - +function multiply(pipe1, pipe2) { + return pipe1 * pipe2; } -function format() { - +function format(pound) { + return `£${pound}`; } -const startingValue = 2 +const startingValue = 2; // Why can this code be seen as bad practice? Comment your answer. -let badCode = +let badCode = format(multiply(add(startingValue, 10), 2)); //badCode has all codes mumbled up in one line// /* BETTER PRACTICE */ -let goodCode = +let sum = add(startingValue, 10); +let product = multiply(sum, 2); +let goodCode = format(product); /* ======= TESTS - DO NOT MODIFY ===== There are some Tests in this file that will help you work out if your code is working. @@ -43,22 +45,24 @@ There are some Tests in this file that will help you work out if your code is wo To run these tests type `node 2-piping.js` into your terminal */ -const util = require('util'); +const util = require("util"); function test(test_name, actual, expected) { - let status; - if (actual === expected) { - status = "PASSED"; - } else { - status = `FAILED: expected: ${util.inspect(expected)} but your code returned: ${util.inspect(actual)}`; - } - - console.log(`${test_name}: ${status}`); + let status; + if (actual === expected) { + status = "PASSED"; + } else { + status = `FAILED: expected: ${util.inspect( + expected + )} but your code returned: ${util.inspect(actual)}`; + } + + console.log(`${test_name}: ${status}`); } -test('add function - case 1 works', add(1,3), 4) -test('add function - case 2 works', add(2.4,5), 7.4) -test('multiply function works', multiply(2,3), 6) -test('format function works', format(16), "£16") -test('badCode variable correctly assigned', badCode, "£24") -test('goodCode variable correctly assigned', goodCode, "£24") +test("add function - case 1 works", add(1, 3), 4); +test("add function - case 2 works", add(2.4, 5), 7.4); +test("multiply function works", multiply(2, 3), 6); +test("format function works", format(16), "£16"); +test("badCode variable correctly assigned", badCode, "£24"); +test("goodCode variable correctly assigned", goodCode, "£24"); diff --git a/week-2/1-exercises/B-boolean-literals/exercise.js b/week-2/1-exercises/B-boolean-literals/exercise.js index 6c5060f..6c675b9 100644 --- a/week-2/1-exercises/B-boolean-literals/exercise.js +++ b/week-2/1-exercises/B-boolean-literals/exercise.js @@ -5,7 +5,10 @@ Add the required variables with the correct boolean values assigned. */ -var codeYourFutureIsGreat = true; +let codeYourFutureIsGreat = true; //Ofcourse, CYF is great// +let mozafarIsCool = false; +let calculationCorrect = true; +let moreThan10Students = false; /* DO NOT EDIT BELOW THIS LINE diff --git a/week-2/1-exercises/C-comparison-operators/exercise.js b/week-2/1-exercises/C-comparison-operators/exercise.js index 58aee1c..19af43e 100644 --- a/week-2/1-exercises/C-comparison-operators/exercise.js +++ b/week-2/1-exercises/C-comparison-operators/exercise.js @@ -5,16 +5,16 @@ The variables should have values that match the expected results. */ -var studentCount = 16; -var mentorCount = 9; -var moreStudentsThanMentors; // finish this statement +let studentCount = 16; +let mentorCount = 9; +let moreStudentsThanMentors = studentCount > mentorCount; // finish this statement -var roomMaxCapacity = 25; -var enoughSpaceInRoom; // finish this statement +let roomMaxCapacity = 25; +let enoughSpaceInRoom = roomMaxCapacity <= 25; // finish this statement var personA = "Daniel"; var personB = "Irina"; -var sameName; // finish this statement +var sameName = personA === personB; // finish this statement /* DO NOT EDIT BELOW THIS LINE diff --git a/week-2/1-exercises/D-predicates/exercise.js b/week-2/1-exercises/D-predicates/exercise.js index f600521..01fc6a7 100644 --- a/week-2/1-exercises/D-predicates/exercise.js +++ b/week-2/1-exercises/D-predicates/exercise.js @@ -4,15 +4,16 @@ Write a predicate to predicates The variables should have values that match the expected results. */ +var number = 5; // Finish the predicate function to test if the passed number is negative (less than zero) function isNegative(number) { - + return numberNegative < 0; } // Finish the predicate function to test if the passed number is between 0 and 10 function isBetweenZeroAnd10(number) { - + return number > 1 && number < 10; } /* @@ -32,4 +33,3 @@ console.log("Is the number between 0 and 10? " + numberBetweenZeroAnd10); Is the number negative? false Is the number between 0 and 10? true */ - diff --git a/week-2/1-exercises/E-conditionals/exercise.js b/week-2/1-exercises/E-conditionals/exercise.js index acbaaa8..b26b0c8 100644 --- a/week-2/1-exercises/E-conditionals/exercise.js +++ b/week-2/1-exercises/E-conditionals/exercise.js @@ -5,10 +5,16 @@ If Daniel is a mentor, print out "Hi, I'm Daniel, I'm a mentor." If Daniel is a student, print out "Hi, I'm Daniel, I'm a student." */ - -var name = "Daniel"; -var danielsRole = "mentor"; - +function status() { + var name = "Daniel"; + var danielsRole = [["mentor"], ["student"]]; + if (danielsRole === danielsRole[0]) { + return "Hi, I'm Daniel, I'm a mentor"; + } + return "Hi, I'm Daniel, I'm a student."; +} +let output = "Hi, I'm Daniel, I'm a mentor"; +console.log(output); /* EXPECTED RESULT --------------- diff --git a/week-2/1-exercises/F-logical-operators/exercise.js b/week-2/1-exercises/F-logical-operators/exercise.js index a8f2945..fd2e2b1 100644 --- a/week-2/1-exercises/F-logical-operators/exercise.js +++ b/week-2/1-exercises/F-logical-operators/exercise.js @@ -11,14 +11,15 @@ var cssLevel = 4; // Finish the statement to check whether HTML, CSS knowledge are above 5 // (hint: use the comparison operator from before) -var htmlLevelAbove5; -var cssLevelAbove5; + +let htmlLevelAbove5 = htmlLevel > 5; +let cssLevelAbove5 = cssLevel > 5; // Finish the next two statement // Use the previous variables and logical operators // Do not "hardcode" the answers -var cssAndHtmlAbove5; -var cssOrHtmlAbove5; +let cssAndHtmlAbove5 = cssLevel > 5 && htmlLevel > 5; +let cssOrHtmlAbove5 = cssLevel > 5 || htmlLevel > 5; /* DO NOT EDIT BELOW THIS LINE @@ -27,10 +28,7 @@ var cssOrHtmlAbove5; console.log("Is Html knowledge above 5?", htmlLevelAbove5); console.log("Is CSS knowledge above 5?", cssLevelAbove5); console.log("Is Html And CSS knowledge above 5?", cssAndHtmlAbove5); -console.log( - "Is either Html or CSS knowledge above 5?", - cssOrHtmlAbove5 -); +console.log("Is either Html or CSS knowledge above 5?", cssOrHtmlAbove5); /* EXPECTED RESULT diff --git a/week-2/1-exercises/F-logical-operators/exercise2.js b/week-2/1-exercises/F-logical-operators/exercise2.js index 6f4199c..bff3ce2 100644 --- a/week-2/1-exercises/F-logical-operators/exercise2.js +++ b/week-2/1-exercises/F-logical-operators/exercise2.js @@ -5,7 +5,33 @@ Update the code so that you get the expected result. */ -function isNegative() {} +function isNegative(number) { + if (number < 0) { + return true; + } + return false; +} + +function isBetween5and10(number) { + if (number >= 5 && number <= 10) { + return true; + } + return false; +} + +function isShortName(name) { + if (name.length < 7) { + return true; + } + return false; +} + +function startsWithD(name) { + if (name[0] === "D") { + return true; + } + return false; +} /* DO NOT EDIT BELOW THIS LINE diff --git a/week-2/1-exercises/G-conditionals-2/exercise-1.js b/week-2/1-exercises/G-conditionals-2/exercise-1.js index 54708ef..8cce2dc 100644 --- a/week-2/1-exercises/G-conditionals-2/exercise-1.js +++ b/week-2/1-exercises/G-conditionals-2/exercise-1.js @@ -7,9 +7,23 @@ */ function negativeOrPositive(number) { - + if (number < 0) { + return "negative"; + } else if (number >= 0) { + return "positive"; + } } +/*An Alternative/ +// function negativeOrPositive(number) { +// if (number < 0) { +// return "negative"; +// } +// if (number >= 0) { +// return "positive"; +// } +// } + /* DO NOT EDIT BELOW THIS LINE --------------------------- */ diff --git a/week-2/1-exercises/G-conditionals-2/exercise-2.js b/week-2/1-exercises/G-conditionals-2/exercise-2.js index 313f3fb..9d12416 100644 --- a/week-2/1-exercises/G-conditionals-2/exercise-2.js +++ b/week-2/1-exercises/G-conditionals-2/exercise-2.js @@ -8,7 +8,12 @@ */ function studentPassed(grade) { - + if (grade < 50) { + return "failed"; + } + if (grade >= 50) { + return "passed"; + } } /* @@ -18,9 +23,9 @@ var grade1 = 49; var grade2 = 50; var grade3 = 100; -console.log("'" + grade1 + "': " + studentPassed(grade1)) -console.log("'" + grade2 + "': " + studentPassed(grade2)) -console.log("'" + grade3 + "': " + studentPassed(grade3)) +console.log("'" + grade1 + "': " + studentPassed(grade1)); +console.log("'" + grade2 + "': " + studentPassed(grade2)); +console.log("'" + grade3 + "': " + studentPassed(grade3)); /* EXPECTED RESULT diff --git a/week-2/1-exercises/G-conditionals-2/exercise-3.js b/week-2/1-exercises/G-conditionals-2/exercise-3.js index a79cf30..d39150d 100644 --- a/week-2/1-exercises/G-conditionals-2/exercise-3.js +++ b/week-2/1-exercises/G-conditionals-2/exercise-3.js @@ -9,7 +9,14 @@ */ function calculateGrade(mark) { - + if (mark >= 80) { + return "A"; + } else if (mark > 60 && mark < 80) { + return "B"; + } else if ((mark = 60 || mark < 50)) { + return "C"; + } + return "F"; } /* @@ -25,7 +32,7 @@ console.log("'" + grade2 + "': " + calculateGrade(grade2)); console.log("'" + grade3 + "': " + calculateGrade(grade3)); console.log("'" + grade4 + "': " + calculateGrade(grade4)); - /* +/* EXPECTED RESULT --------------- '49': F diff --git a/week-2/1-exercises/G-conditionals-2/exercise-4.js b/week-2/1-exercises/G-conditionals-2/exercise-4.js index bd5bb1e..8f3e50e 100644 --- a/week-2/1-exercises/G-conditionals-2/exercise-4.js +++ b/week-2/1-exercises/G-conditionals-2/exercise-4.js @@ -9,7 +9,10 @@ */ function containsCode(sentence) { - + if (sentence.includes("code")) { + return true; + } + return false; } /* @@ -19,11 +22,11 @@ var sentence1 = "code your future"; var sentence2 = "draw your future"; var sentence3 = "design your future"; -console.log("'" + sentence1 + "': " + containsCode(sentence1)) -console.log("'" + sentence2 + "': " + containsCode(sentence2)) -console.log("'" + sentence3 + "': " + containsCode(sentence3)) +console.log("'" + sentence1 + "': " + containsCode(sentence1)); +console.log("'" + sentence2 + "': " + containsCode(sentence2)); +console.log("'" + sentence3 + "': " + containsCode(sentence3)); - /* +/* EXPECTED RESULT --------------- 'code your future': true diff --git a/week-2/1-exercises/H-array-literals/exercise.js b/week-2/1-exercises/H-array-literals/exercise.js index d6dc556..9826af8 100644 --- a/week-2/1-exercises/H-array-literals/exercise.js +++ b/week-2/1-exercises/H-array-literals/exercise.js @@ -4,8 +4,8 @@ Declare some variables assigned to arrays of values */ -var numbers = []; // add numbers from 1 to 10 into this array -var mentors; // Create an array with the names of the mentors: Daniel, Irina and Rares +var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // add numbers from 1 to 10 into this array +var 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/week-2/1-exercises/I-array-properties/exercise.js b/week-2/1-exercises/I-array-properties/exercise.js index f9aec89..f7cceb6 100644 --- a/week-2/1-exercises/I-array-properties/exercise.js +++ b/week-2/1-exercises/I-array-properties/exercise.js @@ -5,8 +5,11 @@ */ -function isEmpty(arr) { - return; // complete this statement +function isEmpty(names, numbers) { + if (names.length === 0) { + return true; // complete this statement + } + return false; } /* diff --git a/week-2/1-exercises/J-array-get-set/exercise.js b/week-2/1-exercises/J-array-get-set/exercise.js index 3b95694..18d072c 100644 --- a/week-2/1-exercises/J-array-get-set/exercise.js +++ b/week-2/1-exercises/J-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/week-2/1-exercises/J-array-get-set/exercises2.js b/week-2/1-exercises/J-array-get-set/exercises2.js index 97f126f..fad6e6b 100644 --- a/week-2/1-exercises/J-array-get-set/exercises2.js +++ b/week-2/1-exercises/J-array-get-set/exercises2.js @@ -6,7 +6,9 @@ - change the first value in the array to the number 1 */ -var numbers = [1, 2, 3]; // Don't change this array literal declaration +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/week-2/2-mandatory/1-fix-functions.js b/week-2/2-mandatory/1-fix-functions.js index d5dfada..919407d 100644 --- a/week-2/2-mandatory/1-fix-functions.js +++ b/week-2/2-mandatory/1-fix-functions.js @@ -1,48 +1,40 @@ // The below functions are syntactically correct but not outputting the right results. // Look at the tests and see how you can fix them. -function mood() { - let isHappy = true; - +function mood(isHappy) { if (isHappy) { return "I am happy"; - } else { - return "I am not happy"; - } + } else return "I am not happy"; } function greaterThan10(num) { - let isBigEnough; - - if (isBigEnough) { + let isBigEnough = 10; + if (num > isBigEnough) { return "num is greater than 10"; - } else { - return "num is not big enough"; - } + } else return "num is not big enough"; } -function sortArray(letters) { - let sortedLetters = letters; - - return sortedLetters; +function sortArray() { + let letters = ["a", "n", "c", "e", "z", "f"]; + sorted = letters.sort().join(""); + return sorted; } -function first5(numbers) { - let sliced; - +function first5() { + let numbers = [1, 2, 3, 4, 5, 6, 7, 8]; + let sliced = numbers.slice(0, 5); return sliced; } function get3rdIndex(arr) { - let index = 3; - let element; - + // let index = 3; + let element = arr[3]; return element; } /* ======= TESTS - DO NOT MODIFY ===== */ -const util = require('util'); +const util = require("util"); function test(test_name, actual, expected) { let status; @@ -57,7 +49,9 @@ function test(test_name, actual, expected) { if (isEqual) { status = "PASSED"; } else { - status = `FAILED: expected: ${util.inspect(expected)} but your function returned: ${util.inspect(actual)}`; + status = `FAILED: expected: ${util.inspect( + expected + )} but your function returned: ${util.inspect(actual)}`; } console.log(`${test_name}: ${status}`); @@ -79,25 +73,32 @@ test("mood function works for true", mood(true), "I am happy"); test("mood function works for false", mood(false), "I am not happy"); test( "greaterThanTen function works for 11", - greaterThan10(11), "num is greater than 10" + greaterThan10(11), + "num is greater than 10" ); test( "greaterThanTen function works for 10", - greaterThan10(10), "num is not big enough" + greaterThan10(10), + "num is not big enough" ); test( "greaterThanTen function works for 9", - greaterThan10(9), "num is not big enough" -); -test( - "sortArray function works", - sortArray(["a", "n", "c", "e", "z", "f"]), ["a", "c", "e", "f", "n", "z"] + greaterThan10(9), + "num is not big enough" ); +test("sortArray function works", sortArray(["a", "n", "c", "e", "z", "f"]), [ + "a", + "c", + "e", + "f", + "n", + "z", +]); let numbers = [1, 2, 3, 4, 5, 6, 7, 8]; test("first5 function works", first5(numbers), [1, 2, 3, 4, 5]); if (!arraysEqual(numbers, [1, 2, 3, 4, 5, 6, 7, 8])) { - console.log("PROBLEM: first5 changed its input array - it shouldn't!") + console.log("PROBLEM: first5 changed its input array - it shouldn't!"); } test( diff --git a/week-2/2-mandatory/2-function-creation.js b/week-2/2-mandatory/2-function-creation.js index 8494bfa..71dbd38 100644 --- a/week-2/2-mandatory/2-function-creation.js +++ b/week-2/2-mandatory/2-function-creation.js @@ -5,7 +5,20 @@ Write a function that: - removes any forward slashes (/) in the strings - makes the string all lowercase */ -function tidyUpString(strArr) {} +function tidyUpString(strArr) { + let trimString; + let removeSlash; + let convertToLowerCase; + for (let i = 0; i < strArr.length; i++) { + trimString = strArr[i].trim(); + removeSlash = trimString.replace("/", ""); + convertToLowerCase = removeSlash.toLowerCase(); + strArr[i] = convertToLowerCase; + } + return strArr; +} + +// used trim(), toLowerCase() and replace("/", "") /* Complete the function to check if the variable `num` satisfies the following requirements: @@ -15,7 +28,12 @@ Complete the function to check if the variable `num` satisfies the following req Tip: use logical operators */ -function validate(num) {} +function validate(num) { + if (typeof num === "number" && num % 2 == 0 && num <= 100) { + return true; + } + return false; +} /* Write a function that returns a copy of the given array arr, but with the element at the given index, index removed. @@ -23,7 +41,8 @@ The function must NOT change the original array, arr. */ function remove(arr, index) { - return; // complete this statement + arr.splice(index, 1); + return arr; } /* @@ -35,12 +54,20 @@ Write a function that: */ function formatPercentage(arr) { - + for (let i = 0; i < arr.length; i++) { + if (arr[i] > 100) { + arr[i] = "100%"; // gives any number above 100 a value of "100%" + } else { + arr[i] = `${parseFloat(arr[i].toFixed(2))}%`; + // arr[i] = Math.round((arr[i] + Number.EPSILON) * 100) / 100 + "%" [alternative method]// + } + } + return arr; } /* ======= TESTS - DO NOT MODIFY ===== */ -const util = require('util'); +const util = require("util"); function test(test_name, actual, expected) { let status; @@ -55,7 +82,9 @@ function test(test_name, actual, expected) { if (isEqual) { status = "PASSED"; } else { - status = `FAILED: expected: ${util.inspect(expected)} but your function returned: ${util.inspect(actual)}`; + status = `FAILED: expected: ${util.inspect( + expected + )} but your function returned: ${util.inspect(actual)}`; } console.log(`${test_name}: ${status}`); @@ -75,12 +104,8 @@ function arraysEqual(a, b) { test( "tidyUpString function works - case 1", - tidyUpString(["/Daniel ", "irina ", " Gordon", "ashleigh "]), [ - "daniel", - "irina", - "gordon", - "ashleigh" - ] + tidyUpString(["/Daniel ", "irina ", " Gordon", "ashleigh "]), + ["daniel", "irina", "gordon", "ashleigh"] ); test( "tidyUpString function works - case 2", @@ -94,28 +119,20 @@ test("validate function works - case 3", validate(17), false); test("validate function works - case 4", validate("Ten"), false); test("validate function works - case 5", validate(108), false); -test( - "remove function works - case 1", - remove([10, 293, 292, 176, 29], 3), [10, 293, 292, 29] -); +test("remove function works - case 1", remove([10, 293, 292, 176, 29], 3), [ + 10, + 293, + 292, + 29, +]); test( "remove function works - case 2", - remove(["a", "b", "c", "d", "e", "f", "g"], 6), [ - "a", - "b", - "c", - "d", - "e", - "f" - ] + remove(["a", "b", "c", "d", "e", "f", "g"], 6), + ["a", "b", "c", "d", "e", "f"] ); test( "formatPercentage function works - case 1", - formatPercentage([23, 18.103, 187.2, 0.372]), [ - "23%", - "18.1%", - "100%", - "0.37%" - ] + formatPercentage([23, 18.103, 187.2, 0.372]), + ["23%", "18.1%", "100%", "0.37%"] ); diff --git a/week-2/2-mandatory/3-playing-computer.js b/week-2/2-mandatory/3-playing-computer.js index 0fa7c04..a43c309 100644 --- a/week-2/2-mandatory/3-playing-computer.js +++ b/week-2/2-mandatory/3-playing-computer.js @@ -1,42 +1,45 @@ /* You have to predict the output of this program WITHOUT EXECUTING IT. - In order to do this, try writing down the value that all variables take during each step of the program execution. - Answer the following questions: - - 1. This program throws an error. Why? (If you can't find it, try executing it). - 2. Remove the line that throws the error. - 3. What is printed to the console? - 4. How many times is "f1" called? - 5. How many times is "f2" called? - 6. What value does the "a" parameter take in the first "f1" call? + 1. This program throws an error. Why? (If you can't find it, try executing it). [ANS: ReferenceError: b is not defined. Thus, I have commented it out ] + 2. Remove the line that throws the error. [ANS: Removed line 28 {console.log(b)] + 3. What is printed to the console? [ANS: 2, 6, 6, 4, 7, 9, 8, 6, 9, 13, 10, 8] + 4. How many times is "f1" called? [ANS: 10, f1 is on line 40. I have used console.log("search", a) on line 41 to check how many times f1 was called] + 5. How many times is "f2" called? [ANS: 2, on line 37] + 6. What value does the "a" parameter take in the first "f1" call? [ANS: 9, I determine this by using console.log("before", a) on line 32] 7. What is the value of the "a" outer variable when "f1" is called for the first time? */ let x = 2; let a = 6; -const f1 = function(a, b) { +const f1 = function (a, b) { return a + b; }; -const f2 = function(a, b) { +const f2 = function (a, b) { return a + b + x; }; console.log(x); console.log(a); -console.log(b); +// console.log(b); //[Ans 1 and Ans 2: this line has returned an error because b is not defined, thus, I have commented it out] for (let i = 0; i < 5; ++i) { + console.log(a); + // console.log("before", a) // [ANS 9: I used this line to check the value of a when f1 is called] a = a + 1; + // console.log("after", a) // [I used this line to check the value of a after] if (i % 2 === 0) { const d = f2(i, x); + //console.log("scan", x); // ANS: 2, I used this line to check how many times times f2 was called// console.log(d); } else { - const e = f1(i, a); + const e = f1(i, a); + //console.log("search", a) // [ANS: 10 times: I run this line of code to determine the number of times a was called.]// console.log(e); + } -} +} \ No newline at end of file diff --git a/week-3/1-exercises/A-array-find/exercise.js b/week-3/1-exercises/A-array-find/exercise.js index d7fd51f..3a09018 100644 --- a/week-3/1-exercises/A-array-find/exercise.js +++ b/week-3/1-exercises/A-array-find/exercise.js @@ -7,9 +7,16 @@ var names = ["Rakesh", "Antonio", "Alexandra", "Andronicus", "Annam", "Mikey", "Anastasia", "Karim", "Ahmed"]; -var longNameThatStartsWithA = findLongNameThatStartsWithA(names); +function isLongNameStart(name) { + for (let i = 0; i < name.length; i++) { + return (name.length > 7 && name[i][0] === "A") + } +} + +var longNameThatStartsWithA = names.find(isLongNameStart); console.log(longNameThatStartsWithA); + /* EXPECTED OUTPUT */ // "Alexandra" diff --git a/week-3/1-exercises/B-array-some/exercise.js b/week-3/1-exercises/B-array-some/exercise.js index 965c052..d05c19e 100644 --- a/week-3/1-exercises/B-array-some/exercise.js +++ b/week-3/1-exercises/B-array-some/exercise.js @@ -8,6 +8,21 @@ var pairsByIndex = [[0, 3], [1, 2], [2, 1], null, [3, 0]]; +var pairs = pairsByIndex.map(function (indexes) { + + const nullCheck = (element) => element === null; + + if (pairsByIndex.some(nullCheck) === true) { + process.exit(1); + } + else { + return [student, mentor]; + } +}) + console.log(pairs) + + + // If there is a null value in the array exit the program with the error code // https://nodejs.org/api/process.html#process_process_exit_code // process.exit(1); @@ -15,7 +30,7 @@ var pairsByIndex = [[0, 3], [1, 2], [2, 1], null, [3, 0]]; var students = ["Islam", "Lesley", "Harun", "Rukmini"]; var mentors = ["Daniel", "Irina", "Mozafar", "Luke"]; -var pairs = pairsByIndex.map(function(indexes) { +var pairs = pairsByIndex.map(function (indexes) { var student = students[indexes[0]]; var mentor = mentors[indexes[1]]; return [student, mentor]; diff --git a/week-3/1-exercises/D-array-filter/exercise.js b/week-3/1-exercises/D-array-filter/exercise.js index 6e32cc6..97d001e 100644 --- a/week-3/1-exercises/D-array-filter/exercise.js +++ b/week-3/1-exercises/D-array-filter/exercise.js @@ -8,12 +8,17 @@ var pairsByIndexRaw = [[0, 3], [1, 2], [2, 1], null, [1], false, "whoops"]; -var pairsByIndex; // Complete this statement +function isAnArray(Array) { + return Array.isArray([]); +} + +var pairsByIndex = pairsByIndexRaw.filter(isAnArray); +// Complete this statement var students = ["Islam", "Lesley", "Harun", "Rukmini"]; var mentors = ["Daniel", "Irina", "Mozafar", "Luke"]; -var pairs = pairsByIndex.map(function(indexes) { +var pairs = pairsByIndex.map(function (indexes) { var student = students[indexes[0]]; var mentor = mentors[indexes[1]]; return [student, mentor]; diff --git a/week-3/2-mandatory/1-oxygen-levels.js b/week-3/2-mandatory/1-oxygen-levels.js index f9d745f..08f9d64 100644 --- a/week-3/2-mandatory/1-oxygen-levels.js +++ b/week-3/2-mandatory/1-oxygen-levels.js @@ -9,8 +9,14 @@ To be safe to land on, a planet needs to have an Oxygen level between 19.5% and Write a function that finds the first safe oxygen level in the array - Oxygen between 19.5% and 23.5% */ -function safeLevels() { - +function safeLevels(arr) { + const convert = arr.map(function (level) { + return parseFloat(level); + }); + const safeLevels = convert.filter(function (n) { + return n > 19.5 && n < 23.5; + }); + return `${safeLevels[0]}%`; } /* ======= TESTS - DO NOT MODIFY ===== */ @@ -19,33 +25,23 @@ const oxygenLevels1 = ["24.2%", "11.3%", "19.9%", "23.1%", "29.3%", "20.2%"]; const oxygenLevels2 = ["30.8%", "23.5%", "18.8%", "19.5%", "20.2%", "31.6%"]; const oxygenLevels3 = ["200%", "21.1%"]; -const util = require('util'); +const util = require("util"); function test(test_name, actual, expected) { - let status; - if (actual === expected) { - status = "PASSED"; - } else { - status = `FAILED: expected: ${util.inspect(expected)} but your function returned: ${util.inspect(actual)}`; - } - - console.log(`${test_name}: ${status}`); + let status; + if (actual === expected) { + status = "PASSED"; + } else { + status = `FAILED: expected: ${util.inspect( + expected + )} but your function returned: ${util.inspect(actual)}`; + } + + console.log(`${test_name}: ${status}`); } -test( - "safeLevels function works - case 1", - safeLevels(oxygenLevels1), - "19.9%" -); - -test( - "safeLevels function works - case 2", - safeLevels(oxygenLevels2), - "20.2%" -); - -test( - "safeLevels function works - case 3", - safeLevels(oxygenLevels3), - "21.1%" -); +test("safeLevels function works - case 1", safeLevels(oxygenLevels1), "19.9%"); + +test("safeLevels function works - case 2", safeLevels(oxygenLevels2), "20.2%"); + +test("safeLevels function works - case 3", safeLevels(oxygenLevels3), "21.1%"); diff --git a/week-3/2-mandatory/2-bush-berries.js b/week-3/2-mandatory/2-bush-berries.js index aca45ad..46b61b1 100644 --- a/week-3/2-mandatory/2-bush-berries.js +++ b/week-3/2-mandatory/2-bush-berries.js @@ -10,10 +10,26 @@ Use the tests to confirm which message to return */ -function bushChecker() { - +function bushChecker(bush) { + if (bush.filter(color => color !== "pink").length > 0) { + return "Toxic! Leave bush alone!" + } +else +return "Bush is safe to eat from" } +// function isNotPink(color) { +// return color !== "pink"; +// } + +// function bushChecker(bush) { +// if (bush.filter(isNotPink).length > 0) { +// return "Toxic! Leave bush alone!" +// } +// else +// return "Bush is safe to eat from" +// } + /* ======= TESTS - DO NOT MODIFY ===== */ let bushBerryColours1 = ["pink", "pink", "pink", "neon", "pink", "transparent"] diff --git a/week-3/2-mandatory/3-space-colonies.js b/week-3/2-mandatory/3-space-colonies.js index 239eddd..3101291 100644 --- a/week-3/2-mandatory/3-space-colonies.js +++ b/week-3/2-mandatory/3-space-colonies.js @@ -1,3 +1,4 @@ + /* The voyagers decide that they quite like this planet, and some of them want to settle there and colonise it. They call the planet "Alpha" and they decide that the FAMILIES whose last names start with 'A' should stay, @@ -8,10 +9,18 @@ NOTE: don't include any element that is not a "family". */ -function colonisers() { - +function landedFamily(element) { + if (element.split(" ")[1] === "family") { + return element[0] === "A"; + } } +function colonisers(voyagers) { + + return voyagers.filter(landedFamily); +}; + + /* ======= TESTS - DO NOT MODIFY ===== */ const voyagers = [ diff --git a/week-3/2-mandatory/4-eligible-students.js b/week-3/2-mandatory/4-eligible-students.js index d8fe052..3ed3d18 100644 --- a/week-3/2-mandatory/4-eligible-students.js +++ b/week-3/2-mandatory/4-eligible-students.js @@ -7,8 +7,14 @@ - Returns an array containing only the names of the who have attended AT LEAST 8 classes */ -function eligibleStudents() { - +function eligibleStudents(arr) { + let attended8Classes = arr.filter(function (name) { + return name[1] >= 8; + }); + let namesOfAttended8 = attended8Classes.map(function (names) { + return names[0]; + }); + return namesOfAttended8; } /* ======= TESTS - DO NOT MODIFY ===== */ @@ -19,9 +25,42 @@ const attendances = [ ["Elamin", 6], ["Adam", 7], ["Tayoa", 11], - ["Nina", 10] -] + ["Nina", 10], +]; + +<<<<<<< HEAD +function arraysEqual(a, b) { + if (a === b) return true; + if (a == null || b == null) return false; + if (a.length != b.length) return false; + + for (let i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) return false; + } + + return true; +} + +function test(test_name, expr) { + let status; + if (expr) { + status = "PASSED"; + } else { + status = "FAILED"; + } + + console.log(`${test_name}: ${status}`); +} +test( + "eligibleStudents function works", + arraysEqual(eligibleStudents(attendances), [ + "Ahmed", + "Clement", + "Tayoa", + "Nina", + ]) +======= const util = require('util'); function test(test_name, actual, expected) { @@ -38,4 +77,5 @@ function test(test_name, actual, expected) { test("eligibleStudents function works", eligibleStudents(attendances), ["Ahmed", "Clement", "Tayoa", "Nina"] +>>>>>>> 8d17c19782cb831f7eeeb6c2adc0555b17d81af4 ); diff --git a/week-3/2-mandatory/5-journey-planner.js b/week-3/2-mandatory/5-journey-planner.js index 816637d..fc2817d 100644 --- a/week-3/2-mandatory/5-journey-planner.js +++ b/week-3/2-mandatory/5-journey-planner.js @@ -7,7 +7,18 @@ NOTE: only the names should be returned, not the means of transport. */ +<<<<<<< HEAD +function journeyPlanner(londonLocations, transportMode) { + const transportLoc = londonLocations.filter(function (transport) { + return transport.includes(transportMode); + }); + const locationName = transportLoc.map(function (location) { + return location[0]; + }); + return locationName; +======= function journeyPlanner() { +>>>>>>> 8d17c19782cb831f7eeeb6c2adc0555b17d81af4 } /* ======= TESTS - DO NOT MODIFY ===== */ @@ -17,10 +28,26 @@ const londonLocations = [ ["Greenwich", "bus", "river boat", "dlr", "air line", "tube"], ["London Bridge", "tube", "river boat"], ["Tower Bridge", "tube", "bus"], +<<<<<<< HEAD + ["Greenwich", "bus", "river boat"], +]; +======= ] +>>>>>>> 8d17c19782cb831f7eeeb6c2adc0555b17d81af4 const util = require('util'); +<<<<<<< HEAD +function test(test_name, expr) { + let status; + if (expr) { + status = "PASSED"; + } else { + status = "FAILED"; + } + + console.log(`${test_name}: ${status}`); +======= function test(test_name, actual, expected) { let status; if (util.isDeepStrictEqual(actual, expected)) { @@ -30,22 +57,46 @@ function test(test_name, actual, expected) { } console.log(`${test_name}: ${status}`); +>>>>>>> 8d17c19782cb831f7eeeb6c2adc0555b17d81af4 } test( "journeyPlanner function works - case 1", +<<<<<<< HEAD + arraysEqual(journeyPlanner(londonLocations, "river boat"), [ + "London Bridge", + "Greenwich", + ]) +======= journeyPlanner(londonLocations, "river boat"), ["Greenwich", "London Bridge"] +>>>>>>> 8d17c19782cb831f7eeeb6c2adc0555b17d81af4 ); test( "journeyPlanner function works - case 2", +<<<<<<< HEAD + arraysEqual(journeyPlanner(londonLocations, "bus"), [ + "Angel", + "Tower Bridge", + "Greenwich", + ]) +======= journeyPlanner(londonLocations, "bus"), ["Angel", "Greenwich", "Tower Bridge"] +>>>>>>> 8d17c19782cb831f7eeeb6c2adc0555b17d81af4 ); test( "journeyPlanner function works - case 3", +<<<<<<< HEAD + arraysEqual(journeyPlanner(londonLocations, "tube"), [ + "Angel", + "London Bridge", + "Tower Bridge", + ]) +======= journeyPlanner(londonLocations, "tube"), ["Angel", "Greenwich", "London Bridge", "Tower Bridge"] +>>>>>>> 8d17c19782cb831f7eeeb6c2adc0555b17d81af4 ); diff --git a/week-3/2-mandatory/6-lane-names.js b/week-3/2-mandatory/6-lane-names.js index ef4e1c5..245047e 100644 --- a/week-3/2-mandatory/6-lane-names.js +++ b/week-3/2-mandatory/6-lane-names.js @@ -4,35 +4,39 @@ Write a function that will return all street names which contain 'Lane' in their name. */ -function getLanes() { - +function getLanes(streetName) { + let streetNameLane = streetName.filter(function (laneName) { + return laneName.includes("Lane"); + }); + return streetNameLane; } /* ======= TESTS - DO NOT MODIFY ===== */ const streetNames = [ - "Abchurch Lane", - "Adam's Court", - "Addle Hill", - "Addle Lane", - "Alban Highwalk" -] + "Abchurch Lane", + "Adam's Court", + "Addle Hill", + "Addle Lane", + "Alban Highwalk", +]; -const util = require('util'); +const util = require("util"); function test(test_name, actual, expected) { - let status; - if (util.isDeepStrictEqual(actual, expected)) { - status = "PASSED"; - } else { - status = `FAILED: expected: ${util.inspect(expected)} but your function returned: ${util.inspect(actual)}`; - } - - console.log(`${test_name}: ${status}`); + let status; + if (util.isDeepStrictEqual(actual, expected)) { + status = "PASSED"; + } else { + status = `FAILED: expected: ${util.inspect( + expected + )} but your function returned: ${util.inspect(actual)}`; + } + + console.log(`${test_name}: ${status}`); } -test( - "getLanes function works", - getLanes(streetNames), - ["Abchurch Lane", "Addle Lane"] -); +test("getLanes function works", getLanes(streetNames), [ + "Abchurch Lane", + "Addle Lane", +]); diff --git a/week-3/2-mandatory/7-password-validator.js b/week-3/2-mandatory/7-password-validator.js index 8f9e597..d558cde 100644 --- a/week-3/2-mandatory/7-password-validator.js +++ b/week-3/2-mandatory/7-password-validator.js @@ -7,10 +7,17 @@ new array with true or false booleans for whether that password was valid or not To be valid, a password must: - Have at least 5 characters. +<<<<<<< HEAD +- Have English uppercase letters (A-Z) +- Have English lowercase letters (a-z) +- Have numbers (0-9) +- Have non-alphanumeric symbols ("!", "#", "$", "%", ".", "*", "&") +======= - Have at least one English uppercase letter (A-Z) - Have at least one English lowercase letter (a-z) - Have at least one number (0-9) - Have at least one non-alphanumeric symbol ("!", "#", "$", "%", ".", "*", "&") +>>>>>>> 8d17c19782cb831f7eeeb6c2adc0555b17d81af4 Passwords must not be any previous password in the passwords array. @@ -23,14 +30,51 @@ PasswordValidationResult= [false, false, false, false, true] */ function validatePasswords(passwords) { - + let checkPasswords = passwords.map((pass, index, array) => { + if ( + pass.length >= 5 && + /[A-Z]/.test(pass) && + /[a-z]/.test(pass) && + /[0-9]/.test(pass) && + /[!#$%.*&]/.test(pass) && + array.indexOf(pass) === index + ) { + return true; + } else { + return false; + } + }); + return checkPasswords; } /* ======= TESTS - DO NOT MODIFY ===== */ -const passwords1 = ["Se%5", "TktE.TJTU", "384#HsHF", "dvyyeyy!5", "tryT3729"] -const passwords2 = ["StUFf27%", "Pl3nty!", "Jai33", "shajsaUA**&&", "Pl3nty!"] +const passwords1 = ["Se%5", "TktE.TJTU", "384#HsHF", "dvyyeyy!5", "tryT3729"]; +const passwords2 = ["StUFf27%", "Pl3nty!", "Jai33", "shajsaUA**&&", "Pl3nty!"]; + +<<<<<<< HEAD +function arraysEqual(a, b) { + if (a === b) return true; + if (a == null || b == null) return false; + if (a.length != b.length) return false; + + for (let i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) return false; + } + + return true; +} + +function test(test_name, expr) { + let status; + if (expr) { + status = "PASSED"; + } else { + status = "FAILED"; + } + console.log(`${test_name}: ${status}`); +======= const util = require('util'); function test(test_name, actual, expected) { @@ -42,10 +86,19 @@ function test(test_name, actual, expected) { } console.log(`${test_name}: ${status}`); +>>>>>>> 8d17c19782cb831f7eeeb6c2adc0555b17d81af4 } test( "validatePasswords function works - case 1", +<<<<<<< HEAD + arraysEqual(validatePasswords(passwords1), [false, false, true, false, false]) +); + +test( + "validatePasswords function works - case 2", + arraysEqual(validatePasswords(passwords2), [true, true, false, false, false]) +======= validatePasswords(passwords1), [false, false, true, false, false] ); @@ -54,4 +107,5 @@ test( "validatePasswords function works - case 2", validatePasswords(passwords2), [true, true, false, false, false] +>>>>>>> 8d17c19782cb831f7eeeb6c2adc0555b17d81af4 ); diff --git a/week-3/3-extra/3-sorting-algorithm.js b/week-3/3-extra/3-sorting-algorithm.js index 3603942..799f96e 100644 --- a/week-3/3-extra/3-sorting-algorithm.js +++ b/week-3/3-extra/3-sorting-algorithm.js @@ -14,7 +14,23 @@ You don't have to worry about making this algorithm work fast! The idea is to ge "think" like a computer and practice your knowledge of basic JavaScript. */ -function sortAges(arr) {} +function sortAges(arr) { + let result = []; + for (let age = 0; age < arr.length; age++) { + if (typeof arr[age] === "number") { + result.push(arr[age]); // filters only numbers and adds to the empty array (result)// + } + } + function sorting(a, b) { + return a - b; +} + return sortAscending = result.sort(sorting); // sorts numbers in ascending order// +} + + + + + /* ======= TESTS - DO NOT MODIFY ===== */