From 7ce0964af851a4a491a7b58581c1332bf3b980ed Mon Sep 17 00:00:00 2001 From: wonder woman Date: Wed, 17 Jun 2020 21:46:14 +0100 Subject: [PATCH 01/18] Tasks 1 - 3 1-exercises 2-mandatory 3-extra --- week-1/1-exercises/B-hello-world/exercise.js | 3 + week-1/1-exercises/C-variables/exercise.js | 4 +- week-1/1-exercises/D-strings/exercise.js | 4 +- .../E-strings-concatenation/exercise.js | 12 ++- .../1-exercises/F-strings-methods/exercise.js | 21 +++++- .../F-strings-methods/exercise2.js | 11 +++ week-1/1-exercises/G-numbers/exercise.js | 12 +++ week-1/1-exercises/I-floats/exercise.js | 9 +++ week-1/1-exercises/J-functions/exercise.js | 7 ++ week-1/1-exercises/J-functions/exercise2.js | 1 + .../K-functions-parameters/exercise.js | 3 +- .../K-functions-parameters/exercise2.js | 3 + .../K-functions-parameters/exercise3.js | 3 + .../K-functions-parameters/exercise4.js | 6 +- .../K-functions-parameters/exercise5.js | 3 + .../L-functions-nested/exercise.js | 73 +++++++++++++++++++ week-1/2-mandatory/1-syntax-errors.js | 16 ++-- week-1/2-mandatory/2-logic-error.js | 7 +- week-1/2-mandatory/3-function-output.js | 5 ++ week-1/2-mandatory/4-tax.js | 40 +++++++++- week-1/3-extra/1-currency-conversion.js | 20 ++++- week-1/3-extra/2-piping.js | 24 ++++-- week-1/3-extra/3-magic-8-ball.js | 35 ++++++++- 23 files changed, 291 insertions(+), 31 deletions(-) diff --git a/week-1/1-exercises/B-hello-world/exercise.js b/week-1/1-exercises/B-hello-world/exercise.js index b179ee9..3b36053 100644 --- a/week-1/1-exercises/B-hello-world/exercise.js +++ b/week-1/1-exercises/B-hello-world/exercise.js @@ -1 +1,4 @@ console.log("Hello world"); +console.log("Hello World. I just started learning JavaScript!"); +console.log("Hello again World"); // error when quotation marks are absent +console.log(100); \ No newline at end of file diff --git a/week-1/1-exercises/C-variables/exercise.js b/week-1/1-exercises/C-variables/exercise.js index a6bbb97..52bcc69 100644 --- a/week-1/1-exercises/C-variables/exercise.js +++ b/week-1/1-exercises/C-variables/exercise.js @@ -1,3 +1,5 @@ // Start by creating a variable `greeting` - +var 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..092d2fc 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` - +var message ="This is a string"; +var messageType = typeof message; console.log(message); +console.log(messageType); diff --git a/week-1/1-exercises/E-strings-concatenation/exercise.js b/week-1/1-exercises/E-strings-concatenation/exercise.js index 2cffa6a..d052dee 100644 --- a/week-1/1-exercises/E-strings-concatenation/exercise.js +++ b/week-1/1-exercises/E-strings-concatenation/exercise.js @@ -1,3 +1,13 @@ // Start by creating a variable `message` +var greetingStart = "Hello, my name is "; +var name = "Daniel"; -console.log(message); +var greeting = greetingStart + name; +console.log(greeting); + +name = "Patrick"; +console.log(greeting); // BUG: will output Daniel + +name = "Patrick"; +var greeting = greetingStart + name; +console.log(greeting); diff --git a/week-1/1-exercises/F-strings-methods/exercise.js b/week-1/1-exercises/F-strings-methods/exercise.js index 2cffa6a..55e2b08 100644 --- a/week-1/1-exercises/F-strings-methods/exercise.js +++ b/week-1/1-exercises/F-strings-methods/exercise.js @@ -1,3 +1,22 @@ // Start by creating a variable `message` +var name = "Daniel"; +var nameLength = name.length; +console.log(nameLength); -console.log(message); +var nameLowerCase = name.toLowerCase(); +console.log(nameLowerCase); + +name = "Patrick"; +nameLength = name.length; // have to repeat this variable so you don't get the nameLength of Daniel +console.log(nameLength); + +var msg = `My name is ${name} and my name is ${nameLength} long.`; +console.log(msg); + +var nameTrim = name.trim(); +name = " Patrick . . . "; +msg = `My name is ${name} and my name is ${nameLength} long.`; +console.log(msg); + +msg = `My name is ${nameTrim} and my name is ${nameLength} long.`; +console.log(msg); \ No newline at end of file diff --git a/week-1/1-exercises/F-strings-methods/exercise2.js b/week-1/1-exercises/F-strings-methods/exercise2.js index b4b4694..c951a94 100644 --- a/week-1/1-exercises/F-strings-methods/exercise2.js +++ b/week-1/1-exercises/F-strings-methods/exercise2.js @@ -1,3 +1,14 @@ const name = " Daniel "; +var nameLength = name.length; +var nameTrim = name.trim(); + +var myName = " Patrick "; +nameLength = myName.length; +var message = `My name is ${myName} and my name is ${nameLength} long.`; +console.log(message); + +nameTrim = myName.trim(); +nameLength = nameTrim.length; +message = `My name is ${nameTrim} and my name is ${nameLength} 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..8b5b0d8 100644 --- a/week-1/1-exercises/G-numbers/exercise.js +++ b/week-1/1-exercises/G-numbers/exercise.js @@ -1 +1,13 @@ // Start by creating a variables `numberOfStudents` and `numberOfMentors` +var age = 30; + +var sum = 10 + 2; +var product = 10 * 2; +var quotient = 10 / 2; +var difference = 10 - 2; + +var numberOfStudents = 15; +var numberOfMentors = 8; +var total = numberOfStudents + numberOfMentors; +var msg = `The total number of students and mentors: ${total}.` +console.log(msg); \ No newline at end of file diff --git a/week-1/1-exercises/I-floats/exercise.js b/week-1/1-exercises/I-floats/exercise.js index a5bbcd8..cbd8b3d 100644 --- a/week-1/1-exercises/I-floats/exercise.js +++ b/week-1/1-exercises/I-floats/exercise.js @@ -1,2 +1,11 @@ var numberOfStudents = 15; var numberOfMentors = 8; +var total = numberOfStudents + numberOfMentors; + +var studentPercent = Math.round(numberOfStudents / total * 100); +var studentMsg = `Percentage students: ${studentPercent}%`; +console.log(studentMsg); + +var mentorPercent = Math.round(numberOfMentors / total * 100); +var mentorMsg = `Percentage mentors: ${mentorPercent}%`; +console.log(mentorMsg); \ No newline at end of file diff --git a/week-1/1-exercises/J-functions/exercise.js b/week-1/1-exercises/J-functions/exercise.js index 0ae5850..4778e88 100644 --- a/week-1/1-exercises/J-functions/exercise.js +++ b/week-1/1-exercises/J-functions/exercise.js @@ -1,7 +1,14 @@ function halve(number) { // complete the function here + return number / 2; } var result = halve(12); console.log(result); + +var result = halve(100); +console.log(result); + +var result = halve(15); +console.log(result); \ No newline at end of file diff --git a/week-1/1-exercises/J-functions/exercise2.js b/week-1/1-exercises/J-functions/exercise2.js index 82ef5e7..468d455 100644 --- a/week-1/1-exercises/J-functions/exercise2.js +++ b/week-1/1-exercises/J-functions/exercise2.js @@ -1,5 +1,6 @@ function triple(number) { // complete function here + return number * 3; } var result = triple(12); diff --git a/week-1/1-exercises/K-functions-parameters/exercise.js b/week-1/1-exercises/K-functions-parameters/exercise.js index 8d5db5e..a4eed9d 100644 --- a/week-1/1-exercises/K-functions-parameters/exercise.js +++ b/week-1/1-exercises/K-functions-parameters/exercise.js @@ -1,6 +1,7 @@ // Complete the function so that it takes input parameters -function multiply() { +function multiply(num1, num2) { // Calculate the result of the function and return it + return num1 * num2; } // Assign the result of calling the function the variable `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..4805ef7 100644 --- a/week-1/1-exercises/K-functions-parameters/exercise2.js +++ b/week-1/1-exercises/K-functions-parameters/exercise2.js @@ -1,4 +1,7 @@ // Declare your function first +function divide(num1, num2) { + return num1 / num2; +} var result = divide(3, 4); diff --git a/week-1/1-exercises/K-functions-parameters/exercise3.js b/week-1/1-exercises/K-functions-parameters/exercise3.js index 537e9f4..8c4243c 100644 --- a/week-1/1-exercises/K-functions-parameters/exercise3.js +++ b/week-1/1-exercises/K-functions-parameters/exercise3.js @@ -1,4 +1,7 @@ // Write your function here +function createGreeting(name) { + return `Hello, my name is ${name}`; +} var greeting = 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..e9270b9 100644 --- a/week-1/1-exercises/K-functions-parameters/exercise4.js +++ b/week-1/1-exercises/K-functions-parameters/exercise4.js @@ -1,5 +1,7 @@ // Declare your function first - +function add(num1, num2) { + return num1 + num2; +} // Call the function and assign to a variable `sum` - +var sum = add(13, 124); console.log(sum); diff --git a/week-1/1-exercises/K-functions-parameters/exercise5.js b/week-1/1-exercises/K-functions-parameters/exercise5.js index 7c5bcd6..01bd81e 100644 --- a/week-1/1-exercises/K-functions-parameters/exercise5.js +++ b/week-1/1-exercises/K-functions-parameters/exercise5.js @@ -1,4 +1,7 @@ // Declare your function here +function createLongGreeting(name, age) { + return `Hello, my name is ${name} and I'm ${age} years old`; +} const greeting = 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..8b4d922 100644 --- a/week-1/1-exercises/L-functions-nested/exercise.js +++ b/week-1/1-exercises/L-functions-nested/exercise.js @@ -1,5 +1,78 @@ +// Exercise 1 +function studentPercent(numberOfStudents, numberOfMentors) { + var total = numberOfStudents + numberOfMentors; + var studentPercent = Math.round(numberOfStudents / total * 100); + return studentPercent; +} + +function mentorPercent(numberOfStudents, numberOfMentors) { + var total = numberOfStudents + numberOfMentors; + var mentorPercent = Math.round(numberOfMentors / total * 100); + return mentorPercent; +} + +// console.log(studentPercent(15, 8)); -> this line tests function studentPercent +// console.log(mentorPercent(15, 8)); -> this line tests function mentorPercent + +function message(numberOfStudents, numberOfMentors) { + var msgStudentPercent = `Percentage students: ${studentPercent(numberOfStudents, numberOfMentors)}%` + var msgMentorPercent = `Percentage mentors: ${mentorPercent(numberOfStudents, numberOfMentors)}%` + return msgStudentPercent + "\n" + msgMentorPercent; +} +console.log(message(15, 8)); + +// Exercise 2 var mentor1 = "Daniel"; var mentor2 = "Irina"; var mentor3 = "Mimi"; var mentor4 = "Rob"; var mentor5 = "Yohannes"; + +var shout = mentor1.toUpperCase(); +var greeting = `HELLO ${shout}`; +console.log(greeting); +var shout = mentor2.toUpperCase(); +var greeting = `HELLO ${shout}`; +console.log(greeting); +var shout = mentor3.toUpperCase(); +var greeting = `HELLO ${shout}`; +console.log(greeting); +var shout = mentor4.toUpperCase(); +var greeting = `HELLO ${shout}`; +console.log(greeting); +var shout = mentor5.toUpperCase(); +var greeting = `HELLO ${shout}`; +console.log(greeting); + +var mentors = "Daniel, Irina, Mimi, Rob, Yohannes" +console.log(mentors); + +var greetings = "HELLO "; +var mentorsArray = [mentor1, mentor2, mentor3, mentor4, mentor5]; +console.log(greetings+mentorsArray[0], greetings+mentorsArray[1], greetings+mentorsArray[2], greetings+mentorsArray[3], greetings+mentorsArray[4]); + +function mentors() { + for (i = 0;i < mentorsArray.length; i++) { + // var SHOUT = greetings + mentorsArray[i]; *** doesn't work *** + // return SHOUT; *** doesn't work, so may as well stick to --> return mentorsArray[i]; *** + return mentorsArray[i]; + } +} +console.log(mentors); + + + +// function mentors() { +// for (var i=0; i < mentorsArray.length; i++) { +// return mentors; +// } +// } +// console.log(mentors()); + + +// function greeting(name) { +// var mentor1 = "Daniel"; +// var name = mentor1.toUpperCase(); +// return `HELLO ${mentor1}`; +// } +// console.log(greeting(daniel)); \ No newline at end of file diff --git a/week-1/2-mandatory/1-syntax-errors.js b/week-1/2-mandatory/1-syntax-errors.js index 6910f28..e2c4475 100644 --- a/week-1/2-mandatory/1-syntax-errors.js +++ b/week-1/2-mandatory/1-syntax-errors.js @@ -2,18 +2,24 @@ // There are syntax errors in this code - can you fix it to pass the tests? -function addNumbers(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 getAddition(a, b) { - total = a ++ b + var total = a + b; // Use string interpolation here - return "The total is %{total}" + return `The total is ${total}`; +} + +function getRemainder(a, b) { + var remainder = a % b; + return `The remainder is ${remainder}`; } /* ======= TESTS - DO NOT MODIFY ===== */ diff --git a/week-1/2-mandatory/2-logic-error.js b/week-1/2-mandatory/2-logic-error.js index 1e0a9d4..a9ad256 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 ===== diff --git a/week-1/2-mandatory/3-function-output.js b/week-1/2-mandatory/3-function-output.js index bbb88a2..8151119 100644 --- a/week-1/2-mandatory/3-function-output.js +++ b/week-1/2-mandatory/3-function-output.js @@ -1,9 +1,11 @@ // Add comments to explain what this function does. You're meant to use Google! +// Math.random returns a random number lower than 1 and then times it by 10. So the output is always < 10. function getNumber() { return Math.random() * 10; } // Add comments to explain what this function does. You're meant to use Google! +// This function joins 2 parameter values. So the output is w1, w2. It can be used to create a new set of array. function s(w1, w2) { return w1.concat(w2); } @@ -11,7 +13,10 @@ function s(w1, w2) { 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 to expect in return + var space = " " + secondWord + " "; + return firstWord.concat(space, thirdWord); } +console.log(concatenate('I', 'love', 'pizza')); /* ======= TESTS - DO NOT MODIFY ===== There are some Tests in this file that will help you work out if your code is working. diff --git a/week-1/2-mandatory/4-tax.js b/week-1/2-mandatory/4-tax.js index 6b84208..6cabde6 100644 --- a/week-1/2-mandatory/4-tax.js +++ b/week-1/2-mandatory/4-tax.js @@ -5,7 +5,19 @@ Sales tax is 20% of the price of the product */ -function calculateSalesTax() {} +function calculateSalesTax(sales) { + var tax = .2; + var salesTax = sales * tax; + var twoDecimals = salesTax.toFixed(2); // to add 2 decimal places + var twoDecimalsNum = parseFloat(twoDecimals); // converts text to number + return sales + twoDecimalsNum; + + // var salesaddedTax = sales * 1.2; + // var twoDecimals = salesaddedTax.toFixed(2); + // return twoDecimals; +} +console.log(calculateSalesTax(17.5)); +console.log(calculateSalesTax(34)); /* CURRENCY FORMATTING @@ -17,7 +29,31 @@ function calculateSalesTax() {} Remember that the prices must include the sales tax (hint: you already wrote a function for this!) */ -function formatCurrency() {} +function formatCurrency(sales) { + function calculateSalesTax(sales) { + var tax = .2; + var salesTax = sales * tax; + var twoDecimals = salesTax.toFixed(2); // to add 2 decimal places + var twoDecimalsNum = parseFloat(twoDecimals); // converts text to number + return sales + twoDecimalsNum; + } + var number = calculateSalesTax(sales); + console.log(new Intl.NumberFormat('en-GB', { + style: 'currency', + currency: 'GBP' + }) + .format(number) + ); +} + +// var number = calculateSalesTax(34); +// console.log(new Intl.NumberFormat('en-GB', { +// style: 'currency', +// currency: 'GBP' +// }) +// .format(number) +// ); + /* ======= TESTS - DO NOT MODIFY ===== There are some Tests in this file that will help you work out if your code is working. diff --git a/week-1/3-extra/1-currency-conversion.js b/week-1/3-extra/1-currency-conversion.js index 7f321d9..d8db477 100644 --- a/week-1/3-extra/1-currency-conversion.js +++ b/week-1/3-extra/1-currency-conversion.js @@ -5,8 +5,10 @@ Write a function that converts a price to USD (exchange rate is 1.4 $ to £) */ -function convertToUSD() {} - +function convertToUSD(ukPrice) { + return ukPrice * 1.4; +} + /* CURRENCY FORMATTING =================== @@ -16,7 +18,19 @@ function convertToUSD() {} Find a way to add 1% to all currency conversions (think about the DRY principle) */ -function convertToBRL() {} +function convertToBRL(ukPrice) { + return (ukPrice * 5.7) * 1.01; +} + +// alternative solution is to use below nested function +function add1PcFee(ukPrice) { + function convertToBRL(ukPrice) { + return (ukPrice * 5.7); + } + return convertToBRL(ukPrice) * 1.01; +} + +console.log(add1PcFee(10)); /* ======= TESTS - DO NOT MODIFY ===== There are some Tests in this file that will help you work out if your code is working. diff --git a/week-1/3-extra/2-piping.js b/week-1/3-extra/2-piping.js index 93c0bf7..2bdb6b7 100644 --- a/week-1/3-extra/2-piping.js +++ b/week-1/3-extra/2-piping.js @@ -16,26 +16,34 @@ the final result to the variable goodCode */ -function add() { - +function add(a, b) { + return a + b; } +console.log(add(1, 3)); +console.log(add(2.4, 5.3)); -function multiply() { - +function multiply(a, b) { + return a * b; } +console.log(multiply(2, 3)); -function format() { - +function format(a) { + return "£" + a; } +console.log(format(16)); const startingValue = 2 // Why can this code be seen as bad practice? Comment your answer. -let badCode = +let badCode = "£" + (startingValue + 10) * 2 +console.log(badCode); /* BETTER PRACTICE */ -let goodCode = +let adding = startingValue + 10; +let multiplying = adding * 2; +let goodCode = "£" + multiplying; +console.log(goodCode); /* ======= TESTS - DO NOT MODIFY ===== There are some Tests in this file that will help you work out if your code is working. diff --git a/week-1/3-extra/3-magic-8-ball.js b/week-1/3-extra/3-magic-8-ball.js index 1bb1089..6982ebe 100644 --- a/week-1/3-extra/3-magic-8-ball.js +++ b/week-1/3-extra/3-magic-8-ball.js @@ -45,7 +45,9 @@ Very doubtful. // This should log "The ball has shaken!" // and return the answer. -function shakeBall() {} +function shakeBall() { + return "The ball has shaken!"; +} // The answer should come from shaking the ball let answer; @@ -55,7 +57,36 @@ let answer; // - positive // - negative // - very negative -function checkAnswer() {} +function checkAnswer(answer) { + if (answer == "It is certain." || + "It is decidedly so." || + "Without a doubt." || + "Yes - definitely." || + "You may rely on it.") { + return "very positive"; + } + else if (answer == "As I see it, yes." || + "Most likely." || + "Outlook good." || + "Yes." || + "Signs point to yes.") { + return "positive"; + } + else if (answer == "Reply hazy, try again." || + "Ask again later." || + "Better not tell you now." || + "Cannot predict now." || + "Concentrate and ask again.") { + return "negative"; + } + else if (answer == "Don't count on it." || + "My reply is no." || + "My sources say no." || + "Outlook not so good." || + "Very doubtful.") { + return "very negative"; + } +} /* ======= TESTS - DO NOT MODIFY ===== There are some Tests in this file that will help you work out if your code is working. From d97712cc7df143a624e923526a64b9ef1007e31c Mon Sep 17 00:00:00 2001 From: wonder woman Date: Sun, 21 Jun 2020 16:28:54 +0100 Subject: [PATCH 02/18] completed 1-exercises --- week-2/1-exercises/A-expressions/README.md | 9 +++++++ week-2/1-exercises/A-expressions/exercise.js | 7 +++++ .../B-boolean-literals/exercise.js | 3 +++ .../C-comparison-operators/README.md | 8 ++++++ .../C-comparison-operators/exercise.js | 6 ++--- week-2/1-exercises/D-predicates/exercise.js | 4 +-- week-2/1-exercises/E-conditionals/exercise.js | 6 +++++ .../F-logical-operators/exercise.js | 8 +++--- .../F-logical-operators/exercise2.js | 27 ++++++++++++++++++- .../G-conditionals-2/exercise-1.js | 6 ++++- .../G-conditionals-2/exercise-2.js | 6 ++++- .../G-conditionals-2/exercise-3.js | 10 ++++++- .../G-conditionals-2/exercise-4.js | 5 +++- .../1-exercises/H-array-literals/exercise.js | 4 +-- .../I-array-properties/exercise.js | 6 ++++- .../1-exercises/J-array-get-set/exercise.js | 4 +-- .../1-exercises/J-array-get-set/exercises2.js | 2 ++ 17 files changed, 102 insertions(+), 19 deletions(-) create mode 100644 week-2/1-exercises/A-expressions/exercise.js diff --git a/week-2/1-exercises/A-expressions/README.md b/week-2/1-exercises/A-expressions/README.md index 9503b6b..0fc7a2d 100644 --- a/week-2/1-exercises/A-expressions/README.md +++ b/week-2/1-exercises/A-expressions/README.md @@ -60,7 +60,16 @@ $ > Notice how when we execute an expression the value it produces is printed below it. When we execute a statement, we see `undefined` printed below. This is because statements don't produce values like expressions, they _do something_. * Write some more expressions in the node console +"hello " + "how is" + " " + "Sue?" +1 + 2 * 3 +("hi guys!") + * Assign some expressions to variables +var greeting = "hello " + "how is" + " " + "Sue?" +var num = 1 + 2 * 3 +var getAttention = ("hi guys!") + * Check the value of the variables +see exercise.js Further reading on using the node console: https://hackernoon.com/know-node-repl-better-dbd15bca0af6 diff --git a/week-2/1-exercises/A-expressions/exercise.js b/week-2/1-exercises/A-expressions/exercise.js new file mode 100644 index 0000000..484e5d2 --- /dev/null +++ b/week-2/1-exercises/A-expressions/exercise.js @@ -0,0 +1,7 @@ +var greeting = "hello " + "how is" + " " + "Sue?"; +var num = 1 + 2 * 3; +var getAttention = ("hi guys!"); + +console.log(greeting); +console.log(num); +console.log(getAttention); \ No newline at end of file diff --git a/week-2/1-exercises/B-boolean-literals/exercise.js b/week-2/1-exercises/B-boolean-literals/exercise.js index 6c5060f..6e0c98c 100644 --- a/week-2/1-exercises/B-boolean-literals/exercise.js +++ b/week-2/1-exercises/B-boolean-literals/exercise.js @@ -6,6 +6,9 @@ */ var codeYourFutureIsGreat = true; +var mozafarIsCool = false; +var calculationCorrect = true; +var moreThan10Students = false; /* DO NOT EDIT BELOW THIS LINE diff --git a/week-2/1-exercises/C-comparison-operators/README.md b/week-2/1-exercises/C-comparison-operators/README.md index fd602d9..295385a 100644 --- a/week-2/1-exercises/C-comparison-operators/README.md +++ b/week-2/1-exercises/C-comparison-operators/README.md @@ -27,3 +27,11 @@ The `>` symbol in the expression is a **comparison operator**. Comparison operat * Open `exercise.js` and follow the instructions. * Open a node console, and write some expressions that use comparison operators +> 1 > 2 +false +> 25 <= 25 +true +> 16 > 9 +true +> 16 !== 9 +true \ No newline at end of file diff --git a/week-2/1-exercises/C-comparison-operators/exercise.js b/week-2/1-exercises/C-comparison-operators/exercise.js index 58aee1c..cdd6a49 100644 --- a/week-2/1-exercises/C-comparison-operators/exercise.js +++ b/week-2/1-exercises/C-comparison-operators/exercise.js @@ -7,14 +7,14 @@ var studentCount = 16; var mentorCount = 9; -var moreStudentsThanMentors; // finish this statement +var moreStudentsThanMentors = studentCount > mentorCount; // finish this statement var roomMaxCapacity = 25; -var enoughSpaceInRoom; // finish this statement +var 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..b9a6d97 100644 --- a/week-2/1-exercises/D-predicates/exercise.js +++ b/week-2/1-exercises/D-predicates/exercise.js @@ -7,12 +7,12 @@ // Finish the predicate function to test if the passed number is negative (less than zero) function isNegative(number) { - + return number < 0; } // Finish the predicate function to test if the passed number is between 0 and 10 function isBetweenZeroAnd10(number) { - + return number >= 0 && number <= 10; } /* diff --git a/week-2/1-exercises/E-conditionals/exercise.js b/week-2/1-exercises/E-conditionals/exercise.js index acbaaa8..c2d19fd 100644 --- a/week-2/1-exercises/E-conditionals/exercise.js +++ b/week-2/1-exercises/E-conditionals/exercise.js @@ -9,6 +9,12 @@ var name = "Daniel"; var danielsRole = "mentor"; +if (danielsRole === "mentor") { + console.log(`Hi, I'm ${name}, I'm a mentor.`); +} else { + console.log(`Hi, I'm ${name}, I'm a student.`); +} + /* 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..eda1fa8 100644 --- a/week-2/1-exercises/F-logical-operators/exercise.js +++ b/week-2/1-exercises/F-logical-operators/exercise.js @@ -11,14 +11,14 @@ 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; +var htmlLevelAbove5 = htmlLevel > 5; +var cssLevelAbove5 = cssLevel > 5; // Finish the next two statement // Use the previous variables and logical operators // Do not "hardcode" the answers -var cssAndHtmlAbove5; -var cssOrHtmlAbove5; +var cssAndHtmlAbove5 = cssLevelAbove5 && htmlLevelAbove5; +var cssOrHtmlAbove5 = cssLevelAbove5 || htmlLevelAbove5; /* DO NOT EDIT BELOW THIS LINE diff --git a/week-2/1-exercises/F-logical-operators/exercise2.js b/week-2/1-exercises/F-logical-operators/exercise2.js index 6f4199c..d44470a 100644 --- a/week-2/1-exercises/F-logical-operators/exercise2.js +++ b/week-2/1-exercises/F-logical-operators/exercise2.js @@ -5,7 +5,32 @@ Update the code so that you get the expected result. */ -function isNegative() {} +function isNegative(num) { + if (num < 0) { + return true; + } return false; +} + +function isBetween5and10(num) { + if (num >= 5 && num <= 10) { + return true; + } return false; +} + +function isShortName(name) { + if (name.length < 7) { + return true; + } return false; +} + +// https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-first-character-in-a-string +function startWithD(name) { + let firstLetter = name[0]; + if (firstLetter === "D") { + return true; + } return false; +} +console.log(startWithD("Daniel")); /* 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..e1b6681 100644 --- a/week-2/1-exercises/G-conditionals-2/exercise-1.js +++ b/week-2/1-exercises/G-conditionals-2/exercise-1.js @@ -7,7 +7,11 @@ */ function negativeOrPositive(number) { - + if (number < 0) { + return "negative"; + } else if (number >= 0) { + return "positive"; + } } /* 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..e824b03 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,11 @@ */ function studentPassed(grade) { - + if (grade < 50) { + return "failed"; + } else if (grade >= 50) { + return "passed"; + } } /* 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..ee7ebb5 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,15 @@ */ function calculateGrade(mark) { - + if (mark >= 80) { + return "A"; + } else if (mark < 80 && mark > 60) { + return "B"; + } else if (mark <= 60 && mark >= 50) { + return "C"; + } else { + return "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..3ac4e1b 100644 --- a/week-2/1-exercises/G-conditionals-2/exercise-4.js +++ b/week-2/1-exercises/G-conditionals-2/exercise-4.js @@ -8,8 +8,11 @@ Hint: Google how to check if a string contains a word */ +// https://www.w3schools.com/jsref/jsref_includes.asp function containsCode(sentence) { - + if (sentence.includes("code")) { + return true; + } return false; } /* 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..cc19185 100644 --- a/week-2/1-exercises/I-array-properties/exercise.js +++ b/week-2/1-exercises/I-array-properties/exercise.js @@ -6,7 +6,11 @@ */ function isEmpty(arr) { - return; // complete this statement + if (arr.length === 0) { + return true; // complete this statement + } else { + 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..0873058 100644 --- a/week-2/1-exercises/J-array-get-set/exercises2.js +++ b/week-2/1-exercises/J-array-get-set/exercises2.js @@ -7,6 +7,8 @@ */ var numbers = [1, 2, 3]; // Don't change this array literal declaration +numbers[3] = 4; +numbers[0] = 1; /* DO NOT EDIT BELOW THIS LINE From e1e5aca53dbbc43dbff095165bce4f5dff8b14d5 Mon Sep 17 00:00:00 2001 From: wonder woman Date: Sun, 21 Jun 2020 17:47:22 +0100 Subject: [PATCH 03/18] Update 1-fix-functions.js --- week-2/2-mandatory/1-fix-functions.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/week-2/2-mandatory/1-fix-functions.js b/week-2/2-mandatory/1-fix-functions.js index 6316fad..e2460dd 100644 --- a/week-2/2-mandatory/1-fix-functions.js +++ b/week-2/2-mandatory/1-fix-functions.js @@ -4,7 +4,7 @@ function mood() { let isHappy = true; - if (isHappy) { + if (isHappy === "true") { return "I am happy"; } else { return "I am not happy"; @@ -13,7 +13,7 @@ function mood() { function greaterThan10() { let num = 10; - let isBigEnough; + let isBigEnough = num >= 10; if (isBigEnough) { return "num is greater than or equal to 10"; @@ -22,23 +22,25 @@ function greaterThan10() { } } +// https://stackoverflow.com/questions/52030110/sorting-strings-in-descending-order-in-javascript-most-efficiently function sortArray() { let letters = ["a", "n", "c", "e", "z", "f"]; - let sortedLetters; + let sortedLetters = letters.sort(); return sortedLetters; } +// https://www.w3schools.com/jsref/jsref_slice_array.asp function first5() { let numbers = [1, 2, 3, 4, 5, 6, 7, 8]; - let sliced; + let sliced = numbers.slice(0, 5); return sliced; } function get3rdIndex(arr) { let index = 3; - let element; + let element = arr[index]; return element; } From 512b9178cafc157baca48acad43ece99e0bd9c7c Mon Sep 17 00:00:00 2001 From: wonder woman Date: Sun, 21 Jun 2020 18:05:11 +0100 Subject: [PATCH 04/18] Update 2-function-creation.js function validate(num) --- week-2/2-mandatory/2-function-creation.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/week-2/2-mandatory/2-function-creation.js b/week-2/2-mandatory/2-function-creation.js index bf7ecfd..672a853 100644 --- a/week-2/2-mandatory/2-function-creation.js +++ b/week-2/2-mandatory/2-function-creation.js @@ -5,6 +5,9 @@ Write a function that: - removes any forward slashes (/) in the strings - makes the string all lowercase */ + +// https://www.w3schools.com/jsref/jsref_trim_string.asp +// https://www.w3schools.com/JSREF/jsref_tolowercase.asp#:~:text=The%20toLowerCase()%20method%20converts,a%20string%20to%20uppercase%20letters. function tidyUpString(strArr) {} /* @@ -15,7 +18,13 @@ 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; + } else { + return false; + } +} /* Write a function that removes an element from an array From 3f27d5c001b44fd326cb8e2c85df6c4ff3185575 Mon Sep 17 00:00:00 2001 From: wonder woman Date: Mon, 22 Jun 2020 01:35:16 +0100 Subject: [PATCH 05/18] Update 2-function-creation.js function tidyUpString(strArr) - bug function remove(arr, index) - passed --- week-2/2-mandatory/2-function-creation.js | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/week-2/2-mandatory/2-function-creation.js b/week-2/2-mandatory/2-function-creation.js index 672a853..e2ad2f7 100644 --- a/week-2/2-mandatory/2-function-creation.js +++ b/week-2/2-mandatory/2-function-creation.js @@ -7,8 +7,21 @@ Write a function that: */ // https://www.w3schools.com/jsref/jsref_trim_string.asp +// http://www.punkchip.com/removing-forward-slashes-from-a-string/ // https://www.w3schools.com/JSREF/jsref_tolowercase.asp#:~:text=The%20toLowerCase()%20method%20converts,a%20string%20to%20uppercase%20letters. -function tidyUpString(strArr) {} +let nameArr = [" /D/an", "Sue/ ", " /Paul "]; + +function tidyUpString(strArr) { + for (let i = 0; i < strArr.length; i++) { + let noSpaces = strArr[i].trim(); + let noSlashes = noSpaces.replace(/\//g, ""); + let lowercase = noSlashes.toLowerCase(); + + return lowercase; + } +} + +console.log(tidyUpString(nameArr)); /* Complete the function to check if the variable `num` satisfies the following requirements: @@ -34,10 +47,16 @@ The function must: - remove the item at the specified index */ +// https://www.freecodecamp.org/news/lets-clear-up-the-confusion-around-the-slice-splice-split-methods-in-javascript-8ba3266c29ae/ +let carList = ["bmw", "volvo", "range", "jag", "toyota"] + function remove(arr, index) { - return; // complete this statement + arr.splice(index, 1); // complete this statement + return arr; } +console.log(remove(carList, 3)); + /* Write a function that: - takes an array of numbers as input From e16377c8c47ac34c3a1bc4419bb8d1944d8affe0 Mon Sep 17 00:00:00 2001 From: wonder woman Date: Tue, 23 Jun 2020 03:01:18 +0100 Subject: [PATCH 06/18] Update 2-function-creation.js function formatPercentage(arr) - bug --- week-2/2-mandatory/2-function-creation.js | 28 +++++++++++++++++------ 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/week-2/2-mandatory/2-function-creation.js b/week-2/2-mandatory/2-function-creation.js index e2ad2f7..6131c9c 100644 --- a/week-2/2-mandatory/2-function-creation.js +++ b/week-2/2-mandatory/2-function-creation.js @@ -48,7 +48,7 @@ The function must: */ // https://www.freecodecamp.org/news/lets-clear-up-the-confusion-around-the-slice-splice-split-methods-in-javascript-8ba3266c29ae/ -let carList = ["bmw", "volvo", "range", "jag", "toyota"] +let carList = ["bmw", "volvo", "range", "jag", "toyota"]; function remove(arr, index) { arr.splice(index, 1); // complete this statement @@ -64,10 +64,24 @@ Write a function that: - the numbers must be rounded to 2 decimal places - numbers greater 100 must be replaced with 100 */ - +let num = [10.128, 101.223, 20, 30, 40, 111]; function formatPercentage(arr) { - + for (let i = 0; i < arr.length; i++) { + for (let j = 0; j < arr.length; j++) { + if (arr[i] > 100) { + let check100 = 100; + return check100; + } else { + check100 = arr[i]; + return check100; + } + } + let twoDecimals = check100.toFixed(2); + let addPercent = twoDecimals + "%"; + return addPercent; + } } +console.log(formatPercentage(num)); /* ======= TESTS - DO NOT MODIFY ===== */ @@ -100,7 +114,7 @@ test( "daniel", "irina", "gordon", - "ashleigh" + "ashleigh", ]) ); test( @@ -129,7 +143,7 @@ test( "c", "d", "e", - "f" + "f", ]) ); @@ -139,6 +153,6 @@ test( "23%", "18%", "100%", - "0.37%" + "0.37%", ]) -); \ No newline at end of file +); From 042bfcb25374bf53e36a980245919d494ddee831 Mon Sep 17 00:00:00 2001 From: wonder woman Date: Wed, 24 Jun 2020 08:14:41 +0100 Subject: [PATCH 07/18] Update 2-function-creation.js: debugged function tidyUpString(strArr) function works but the TEST output is FAILED - not sure why --- week-2/2-mandatory/2-function-creation.js | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/week-2/2-mandatory/2-function-creation.js b/week-2/2-mandatory/2-function-creation.js index 6131c9c..59723f9 100644 --- a/week-2/2-mandatory/2-function-creation.js +++ b/week-2/2-mandatory/2-function-creation.js @@ -16,12 +16,11 @@ function tidyUpString(strArr) { let noSpaces = strArr[i].trim(); let noSlashes = noSpaces.replace(/\//g, ""); let lowercase = noSlashes.toLowerCase(); - - return lowercase; + console.log(lowercase); } } -console.log(tidyUpString(nameArr)); +tidyUpString(nameArr); /* Complete the function to check if the variable `num` satisfies the following requirements: @@ -83,6 +82,17 @@ function formatPercentage(arr) { } console.log(formatPercentage(num)); +function greaterThan100(num) { + let greaterThan100 = num[1] > 100; + + if (greaterThan100) { + return 100; + } else { + return num[1]; + } +} +console.log(greaterThan100(num)); + /* ======= TESTS - DO NOT MODIFY ===== */ function arraysEqual(a, b) { From 856a276918dc8d0a6a6af3a11259e68e69d72ae9 Mon Sep 17 00:00:00 2001 From: wonder woman Date: Wed, 24 Jun 2020 10:04:04 +0100 Subject: [PATCH 08/18] Update 2-function-creation.js: Last task I broke up the task, created 3 functions Next step: I need to get the three functions to work the whole array instead of just one array item. --- week-2/2-mandatory/2-function-creation.js | 46 +++++++++++++++-------- 1 file changed, 31 insertions(+), 15 deletions(-) diff --git a/week-2/2-mandatory/2-function-creation.js b/week-2/2-mandatory/2-function-creation.js index 59723f9..53aeb6a 100644 --- a/week-2/2-mandatory/2-function-creation.js +++ b/week-2/2-mandatory/2-function-creation.js @@ -21,7 +21,7 @@ function tidyUpString(strArr) { } tidyUpString(nameArr); - +console.log("----------"); /* Complete the function to check if the variable `num` satisfies the following requirements: - is a number @@ -47,7 +47,7 @@ The function must: */ // https://www.freecodecamp.org/news/lets-clear-up-the-confusion-around-the-slice-splice-split-methods-in-javascript-8ba3266c29ae/ -let carList = ["bmw", "volvo", "range", "jag", "toyota"]; +let carList = ["bmw", "volvo", "range", "jaguar", "toyota"]; function remove(arr, index) { arr.splice(index, 1); // complete this statement @@ -55,7 +55,7 @@ function remove(arr, index) { } console.log(remove(carList, 3)); - +console.log("----------"); /* Write a function that: - takes an array of numbers as input @@ -63,24 +63,24 @@ Write a function that: - the numbers must be rounded to 2 decimal places - numbers greater 100 must be replaced with 100 */ -let num = [10.128, 101.223, 20, 30, 40, 111]; +let num = [10.128, 101.223, 20, 30, 111]; + function formatPercentage(arr) { for (let i = 0; i < arr.length; i++) { - for (let j = 0; j < arr.length; j++) { - if (arr[i] > 100) { - let check100 = 100; - return check100; - } else { - check100 = arr[i]; - return check100; - } + if (arr[i] > 100) { + let check100 = 100; + return check100; + } else { + check100 = arr[i]; + return check100; } - let twoDecimals = check100.toFixed(2); - let addPercent = twoDecimals + "%"; - return addPercent; } } console.log(formatPercentage(num)); +console.log("----------"); +// let twoDecimals = check100.toFixed(2); +// let addPercent = twoDecimals + "%"; +// return addPercent; function greaterThan100(num) { let greaterThan100 = num[1] > 100; @@ -92,6 +92,22 @@ function greaterThan100(num) { } } console.log(greaterThan100(num)); +console.log("----------"); + +// https://stackoverflow.com/questions/19674992/how-to-use-a-return-value-in-another-function-in-javascript +function addTwoDecimals() { + let twoDecimals = greaterThan100(num); + return twoDecimals.toFixed(2); +} +console.log(addTwoDecimals()); +console.log("----------"); + +function addPercent() { + let percent = addTwoDecimals() + "%"; + return percent +} +console.log(addPercent()); +console.log("----------"); /* ======= TESTS - DO NOT MODIFY ===== */ From 896a6563ddaaaf0a7c04c498a6ec37d7f5b16341 Mon Sep 17 00:00:00 2001 From: wonder woman Date: Thu, 25 Jun 2020 04:37:40 +0100 Subject: [PATCH 09/18] Update 3-playing-computer.js I am not sure if I have answered correctly Q6 and Q7 because it adds up to 8, not 9 as per Debug Console result. --- week-2/2-mandatory/3-playing-computer.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/week-2/2-mandatory/3-playing-computer.js b/week-2/2-mandatory/3-playing-computer.js index 0fa7c04..a63d837 100644 --- a/week-2/2-mandatory/3-playing-computer.js +++ b/week-2/2-mandatory/3-playing-computer.js @@ -7,12 +7,12 @@ 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? - 7. What is the value of the "a" outer variable when "f1" is called for the first time? + 2. Remove the line that throws the error. Line 31 + 3. What is printed to the console? 2, 6, 4, 9, 6, 13, 8 + 4. How many times is "f1" called? 2 + 5. How many times is "f2" called? 3 + 6. What value does the "a" parameter take in the first "f1" call? i = 1 + 7. What is the value of the "a" outer variable when "f1" is called for the first time? a = 6 + 1 = 7 */ let x = 2; @@ -28,7 +28,7 @@ const f2 = function(a, b) { console.log(x); console.log(a); -console.log(b); +// console.log(b); for (let i = 0; i < 5; ++i) { a = a + 1; From 7df72d270c1079c71a05b1009b7364a9bef743e5 Mon Sep 17 00:00:00 2001 From: wonder woman Date: Thu, 25 Jun 2020 07:41:49 +0100 Subject: [PATCH 10/18] Update 4-sorting-algorithm.js I used the built-in Javascript filter and sort methods instead of using Hard Mode. --- week-2/2-mandatory/4-sorting-algorithm.js | 24 ++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/week-2/2-mandatory/4-sorting-algorithm.js b/week-2/2-mandatory/4-sorting-algorithm.js index 3603942..5c2afe3 100644 --- a/week-2/2-mandatory/4-sorting-algorithm.js +++ b/week-2/2-mandatory/4-sorting-algorithm.js @@ -14,7 +14,29 @@ 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) {} +/* +Example of filter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter +let words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; +let result = words.filter(word => word.length > 6); +console.log(result); +*/ + +// filter method https://www.youtube.com/watch?v=4_iT6EGkQfk +let ages = ["28", 100, 60, 55, "75", "🍕", "Elamin"]; +let filteredAges = ages.filter(age => typeof age ==="number"); +console.log(filteredAges); + +// sort method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort +filteredAges.sort((a, b) => a - b); +console.log(filteredAges); + +// put the above filter and sort chunks into function below +function sortAges(arr) { + let filteredArr = arr.filter(arrItem => typeof arrItem === "number"); + let sortArr = filteredArr.sort((a, b) => a - b); + return sortArr; +} +console.log(sortAges(ages)); /* ======= TESTS - DO NOT MODIFY ===== */ From c6d4aff75fc4d1a7d2d9234a4a333be47073ccaa Mon Sep 17 00:00:00 2001 From: wonder woman Date: Sat, 27 Jun 2020 10:04:20 +0100 Subject: [PATCH 11/18] Update 2-function-creation.js revised tidyUpString and formarPercentage Created new js files to test solutions with different collaborators. --- week-2/2-mandatory/2-function-creation.js | 86 ++++++++++++--- week-2/2-mandatory/AC-formatPercentage.js | 40 +++++++ week-2/2-mandatory/AK-formatPercentage-v2.js | 108 +++++++++++++++++++ week-2/2-mandatory/AK-formatPercentage.js | 59 ++++++++++ week-2/2-mandatory/JV-tidyUpString.js | 80 ++++++++++++++ 5 files changed, 358 insertions(+), 15 deletions(-) create mode 100644 week-2/2-mandatory/AC-formatPercentage.js create mode 100644 week-2/2-mandatory/AK-formatPercentage-v2.js create mode 100644 week-2/2-mandatory/AK-formatPercentage.js create mode 100644 week-2/2-mandatory/JV-tidyUpString.js diff --git a/week-2/2-mandatory/2-function-creation.js b/week-2/2-mandatory/2-function-creation.js index 53aeb6a..05df998 100644 --- a/week-2/2-mandatory/2-function-creation.js +++ b/week-2/2-mandatory/2-function-creation.js @@ -12,15 +12,16 @@ Write a function that: let nameArr = [" /D/an", "Sue/ ", " /Paul "]; function tidyUpString(strArr) { + let newArray = []; for (let i = 0; i < strArr.length; i++) { let noSpaces = strArr[i].trim(); let noSlashes = noSpaces.replace(/\//g, ""); let lowercase = noSlashes.toLowerCase(); - console.log(lowercase); + newArray[i] = lowercase; } + return newArray; } - -tidyUpString(nameArr); +console.log(tidyUpString(nameArr)); console.log("----------"); /* Complete the function to check if the variable `num` satisfies the following requirements: @@ -68,23 +69,20 @@ let num = [10.128, 101.223, 20, 30, 111]; function formatPercentage(arr) { for (let i = 0; i < arr.length; i++) { if (arr[i] > 100) { - let check100 = 100; - return check100; - } else { - check100 = arr[i]; - return check100; + arr[i] = 100; } + arr[i] = Math.floor(arr[i] * 100) / 100; + arr[i] = `${arr[i]}%`; } + return arr; } -console.log(formatPercentage(num)); + console.log("----------"); -// let twoDecimals = check100.toFixed(2); -// let addPercent = twoDecimals + "%"; -// return addPercent; +/* this chunk works as a standalone without the for loop so I keep it as reference. function greaterThan100(num) { let greaterThan100 = num[1] > 100; - + if (greaterThan100) { return 100; } else { @@ -92,22 +90,80 @@ function greaterThan100(num) { } } console.log(greaterThan100(num)); -console.log("----------"); +*/ +/* this chunk works as a standalone without the for loop // https://stackoverflow.com/questions/19674992/how-to-use-a-return-value-in-another-function-in-javascript function addTwoDecimals() { let twoDecimals = greaterThan100(num); return twoDecimals.toFixed(2); } console.log(addTwoDecimals()); -console.log("----------"); +*/ +/* this chunk works as a standalone without the for loop function addPercent() { let percent = addTwoDecimals() + "%"; return percent } console.log(addPercent()); +*/ +/* +function greaterThan100(num) { + + for (let i = 0; i < num.length; i++) { + let greaterThan100 = num[i] > 100; + if (greaterThan100) { + // return 100; + console.log(num[i] = 100); + } else { + // return num[i]; + console.log(num[i]); + } + } +} +console.log(greaterThan100(num)); +console.log("----------"); +*/ +// https://stackoverflow.com/questions/19674992/how-to-use-a-return-value-in-another-function-in-javascript +/*let num2 = greaterThan100(num); + +function addTwoDecimals(num2) { + for (let i = 0; i < num2.length; i++) { + console.log(num2[i].toFixed(2)); + } +} +console.log(addTwoDecimals(num2)); +console.log("----------"); +/* +let num3 = addTwoDecimals(num2); + +function addPercent(num3) { + for (let i = 0; i < num3.length; i++) { + console.log(num3[i] + "%"); + } + //let percent = addTwoDecimals() + "%"; + //return percent +} +//console.log(addPercent()); console.log("----------"); +*/ + +/* +function formatPercentage(arr) { + for (let i = 0; i < arr.length; i++) { + let testFinal = arr[i]; + if (testFinal > 100) { + testFinal = 100; + } + testFinal = testFinal.toFixed(2); + testFinal = testFinal + "%"; + arr[i] = testFinal; + } + console.log(arr); + return arr; +} +*/ /* ======= TESTS - DO NOT MODIFY ===== */ diff --git a/week-2/2-mandatory/AC-formatPercentage.js b/week-2/2-mandatory/AC-formatPercentage.js new file mode 100644 index 0000000..ea67aca --- /dev/null +++ b/week-2/2-mandatory/AC-formatPercentage.js @@ -0,0 +1,40 @@ +let num = [10.128, 101.223, 20, 30, 111]; +/* +function greaterThan100(num) { + for (i = 0; i < num.length; i++) { + if (num[i] > 100) { + num[i] = 100; + } else { + num[i]; + } + return num; + } +} + +function addTwoDecimals(num){ + num2 = greaterThan100(num); + var x = 0; + var len = num2.length; + while(x < len){ + num2[x] = num2[x].toFixed(2); + } + return num2; + } + var num = [10.128, 101.223, 20, 30, 111]; + console.log(num); + greaterThan100(num); + addTwoDecimals(num); +*/ +function formatPercentage(arr) { + let arrString = [] + for(let i = 0; i < arr.length; i++){ + //checks whether the number is greater than 100,if so replaces to 100 + if(arr[i] > 100){ + arr[i] = 100; + } + //.toFixed(2) keeps the number to 2 decimals + //with Template literals you can place the percentages behind each number and converts it at the same time to strings + arrString[i] = `${arr[i].toFixed(2)}%`; + } + return arrString; + } \ No newline at end of file diff --git a/week-2/2-mandatory/AK-formatPercentage-v2.js b/week-2/2-mandatory/AK-formatPercentage-v2.js new file mode 100644 index 0000000..f34debe --- /dev/null +++ b/week-2/2-mandatory/AK-formatPercentage-v2.js @@ -0,0 +1,108 @@ +/* +Write a function that: +- takes an array of numbers as input +- returns an array of strings formatted as percentages (e.g. 10 => "10%") +- the numbers must be rounded to 2 decimal places +- numbers greater 100 must be replaced with 100 +*/ + +// number > 100 to be replaced with 100 +// let num = 120; +/* +if (num > 100) { + num = 100; +} + +// round the numbers to 2 decimal places + +num = Math.floor(num * 100) / 100; + +console.log(num); +// return an array with % +num = num + "%"; +console.log(num); +*/ +function formatPercentage(arr) { + for (let i = 0; i < arr.length; i++) { + if (arr[i] > 100) { + arr[i] = 100; + } + arr[i] = Math.floor(arr[i] * 100) / 100; + arr[i] = arr[i] + "%"; + } + return arr; +} + +/* ======= TESTS - DO NOT MODIFY ===== */ + +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( + "tidyUpString function works - case 1", + arraysEqual(tidyUpString(["/Daniel ", "irina ", " Gordon", "ashleigh "]), [ + "daniel", + "irina", + "gordon", + "ashleigh", + ]) + ); + test( + "tidyUpString function works - case 2", + arraysEqual( + tidyUpString([" /Sanyia ", " Michael ", "AnTHonY ", " Tim "]), + ["sanyia", "michael", "anthony", "tim"] + ) + ); + + test("validate function works - case 1", validate(10) === true); + test("validate function works - case 2", validate(18) === true); + 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", + arraysEqual(remove([10, 293, 292, 176, 29], 3), [10, 293, 292, 29]) + ); + test( + "remove function works - case 1", + arraysEqual(remove(["a", "b", "c", "d", "e", "f", "g"], 6), [ + "a", + "b", + "c", + "d", + "e", + "f", + ]) + ); + */ +test( + "formatPercentage function works - case 1", + arraysEqual(formatPercentage([23, 18, 187.2, 0.372]), [ + "23%", + "18%", + "100%", + "0.37%", + ]) +); diff --git a/week-2/2-mandatory/AK-formatPercentage.js b/week-2/2-mandatory/AK-formatPercentage.js new file mode 100644 index 0000000..c18522d --- /dev/null +++ b/week-2/2-mandatory/AK-formatPercentage.js @@ -0,0 +1,59 @@ +/* +Write a function that: +- takes an array of numbers as input +- returns an array of strings formatted as percentages (e.g. 10 => "10%") +- the numbers must be rounded to 2 decimal places +- numbers greater 100 must be replaced with 100 +*/ +let num = [10.128, 101.223, 20, 30, 111]; + +function formatPercentage(arr) {} + +let test = 101.223; +console.log(test.toFixed(2)); +// if number > 100, then replace with 100 +if (test > 100) { + test = 100; +} +console.log(test); + +// two decimal places +// Math.floor +// toFixed +let test1 = 10.128; +console.log(test1.toFixed(2)); + +// convert to a string and add % to the string value +let test3 = 100; +let result = test3 + "%"; +console.log(result); + +// testFinal +let array = [10.128, 101.223, 20, 30, 111]; + +/* +for (let i = 0; i < arr.length; i++) { + let testFinal = arr[i]; + if (testFinal > 100) { + testFinal = 100; + } + testFinal = testFinal.toFixed(2); + testFinal = testFinal + "%"; + arr[i] = testFinal; +} +*/ +//console.log(arr); + +function formatPercentage(arr) { + for (let i = 0; i < arr.length; i++) { + let testFinal = arr[i]; + if (testFinal > 100) { + testFinal = 100; + } + testFinal = testFinal.toFixed(2); + testFinal = testFinal + "%"; + arr[i] = testFinal; + } + console.log(arr); + return arr; +} diff --git a/week-2/2-mandatory/JV-tidyUpString.js b/week-2/2-mandatory/JV-tidyUpString.js new file mode 100644 index 0000000..654b97d --- /dev/null +++ b/week-2/2-mandatory/JV-tidyUpString.js @@ -0,0 +1,80 @@ +/* +Write a function that: +- takes an array of strings as input +- removes any spaces in the beginning or end of the strings +- removes any forward slashes (/) in the strings +- makes the string all lowercase +*/ + +/* my original version +function tidyUpString(strArr) { + for (let i = 0; i < strArr.length; i++) { + let noSpaces = strArr[i].trim(); + let noSlashes = noSpaces.replace(/\//g, ""); + let lowercase = noSlashes.toLowerCase(); + console.log(lowercase); + } +} +tidyUpString(nameArr); +*/ + +let nameArr = [" /D/an", "Sue/ ", " /Paul "]; + +// Jacques' version +function tidyUpString(strArr) { + // let removeSpace; + // let replaceString; + // let changeToLowerCase; + let newArray = []; + for (let i = 0; i < strArr.length; i++) { + let removeSpace = strArr[i].trim(); + let replaceString = removeSpace.replace(/\//g, ""); + let changeToLowerCase = replaceString.toLowerCase(); + newArray[i] = changeToLowerCase; + } + return newArray; + } + + console.log(tidyUpString(nameArr)); + + /* ======= TESTS - DO NOT MODIFY ===== */ + +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( + "tidyUpString function works - case 1", + arraysEqual(tidyUpString(["/Daniel ", "irina ", " Gordon", "ashleigh "]), [ + "daniel", + "irina", + "gordon", + "ashleigh", + ]) + ); + test( + "tidyUpString function works - case 2", + arraysEqual( + tidyUpString([" /Sanyia ", " Michael ", "AnTHonY ", " Tim "]), + ["sanyia", "michael", "anthony", "tim"] + ) + ); \ No newline at end of file From 6e3c6152bc1cde4a289e2f5ceeb121018448c286 Mon Sep 17 00:00:00 2001 From: wonder woman Date: Sat, 27 Jun 2020 17:51:08 +0100 Subject: [PATCH 12/18] Update Extra - 1-radio-stations.js completed part 1: function getAvailableStations() --- week-2/3-extra/1-radio-stations.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/week-2/3-extra/1-radio-stations.js b/week-2/3-extra/1-radio-stations.js index 95c0e56..1192c6b 100644 --- a/week-2/3-extra/1-radio-stations.js +++ b/week-2/3-extra/1-radio-stations.js @@ -14,14 +14,23 @@ */ // `getAllFrequencies` goes here +// NOTES: https://dev.to/ycmjason/how-to-create-range-in-javascript-539i +function getAllFrequencies(start, end) { + let frequencies = []; + for (let i = start; i <=end; i++) { + frequencies.push(i); + } + return frequencies; +} +console.log(getAllFrequencies(87, 108)); /** * Next, let's write a function that gives us only the frequencies that are radio stations. * Call this function `getStations`. * * This function should: * - Get the available frequencies from `getAllFrequencies` - * - There is a helper function called isRadioFrequency that takes an integer as an argument and returns a boolean. + * - There is a helper function called isRadioStation that takes an integer as an argument and returns a boolean. * - Return only the frequencies that are radio stations. */ // `getStations` goes here From 315dc68be33fa42713a5b999d2655e12684495d7 Mon Sep 17 00:00:00 2001 From: wonder woman Date: Sun, 28 Jun 2020 21:59:10 +0100 Subject: [PATCH 13/18] Update 1-exercises some completed, some have errors --- week-3/1-exercises/A-array-find/exercise.js | 7 ++++ week-3/1-exercises/B-array-some/exercise.js | 12 ++++++ week-3/1-exercises/C-array-every/exercise.js | 18 ++++++++- week-3/1-exercises/E-array-map/exercise.js | 40 +++++++++++++++++++ .../1-exercises/F-array-forEach/exercise.js | 16 ++++++++ .../1-exercises/G-array-methods/exercise.js | 2 +- .../1-exercises/G-array-methods/exercise2.js | 2 +- .../1-exercises/H-array-methods-2/exercise.js | 4 +- .../H-array-methods-2/exercise2.js | 4 +- .../H-array-methods-2/exercise3.js | 2 +- week-3/2-mandatory/1-oxygen-levels.js | 5 ++- 11 files changed, 103 insertions(+), 9 deletions(-) diff --git a/week-3/1-exercises/A-array-find/exercise.js b/week-3/1-exercises/A-array-find/exercise.js index d7fd51f..fb55cf4 100644 --- a/week-3/1-exercises/A-array-find/exercise.js +++ b/week-3/1-exercises/A-array-find/exercise.js @@ -7,6 +7,13 @@ var names = ["Rakesh", "Antonio", "Alexandra", "Andronicus", "Annam", "Mikey", "Anastasia", "Karim", "Ahmed"]; +function isLongName(name) { + return name.length > 7; +} + +var longName = names.find(isLongName); +console.log(longName); + var longNameThatStartsWithA = findLongNameThatStartsWithA(names); console.log(longNameThatStartsWithA); diff --git a/week-3/1-exercises/B-array-some/exercise.js b/week-3/1-exercises/B-array-some/exercise.js index 965c052..91275f1 100644 --- a/week-3/1-exercises/B-array-some/exercise.js +++ b/week-3/1-exercises/B-array-some/exercise.js @@ -12,6 +12,17 @@ var pairsByIndex = [[0, 3], [1, 2], [2, 1], null, [3, 0]]; // https://nodejs.org/api/process.html#process_process_exit_code // process.exit(1); +function isNull(pairsByIndex) { + return pairsByIndex === null; +} + +var containsNull = pairsByIndex.some(isNull); +console.log(containsNull); + +if (containsNull) { + process.exit(1); +} + var students = ["Islam", "Lesley", "Harun", "Rukmini"]; var mentors = ["Daniel", "Irina", "Mozafar", "Luke"]; @@ -22,3 +33,4 @@ var pairs = pairsByIndex.map(function(indexes) { }); console.log(pairs); + diff --git a/week-3/1-exercises/C-array-every/exercise.js b/week-3/1-exercises/C-array-every/exercise.js index b515e94..46545e3 100644 --- a/week-3/1-exercises/C-array-every/exercise.js +++ b/week-3/1-exercises/C-array-every/exercise.js @@ -5,7 +5,23 @@ var students = ["Omar", "Austine", "Dany", "Swathi", "Lesley", "Rukmini"]; var group = ["Austine", "Dany", "Swathi", "Daniel"]; -var groupIsOnlyStudents; // complete this statement +// https://gomakethings.com/how-to-check-if-two-arrays-are-equal-with-vanilla-js/ +var arraysMatch = function (students, group) { + + // Check if the arrays are the same length + if (students.length !== group.length) return false; + + // Check if all items exist and are in the same order + for (let i = 0; i < students.length; i++) { + if (students[i] !== group[i]) return false; + } + + //Otherwise, return false + return true; +} +console.log(arraysMatch); + +var groupIsOnlyStudents = arraysMatch; // complete this statement if (groupIsOnlyStudents) { console.log("The group contains only students"); diff --git a/week-3/1-exercises/E-array-map/exercise.js b/week-3/1-exercises/E-array-map/exercise.js index 2835e92..6d697c2 100644 --- a/week-3/1-exercises/E-array-map/exercise.js +++ b/week-3/1-exercises/E-array-map/exercise.js @@ -3,3 +3,43 @@ var numbers = [0.1, 0.2, 0.3, 0.4, 0.5]; +function times100(arr) { + return arr * 100; +} + +var numbersTimes100 = numbers.map(times100); +console.log(numbersTimes100); + + +// Callback Function +var numbersTimes200 = numbers.map(function times100(arr) { + return arr * 200; +}); +console.log(numbersTimes200); + + +//We can make this shorter by removing the function name. We can do this because we are not using the function +//anywhere else in the code, so we do not need the function name to reference it. +var numbersTimes300 = numbers.map(function(arr) { + return arr * 300; +}); +console.log(numbersTimes300); + + +// We can make this code even shorter still. In the latest versions of JavaScript a way of declaring functions was +// introduced called _arrow functions_. +// The arrow function syntax lets you declare a function without the `function` keyword. (There are some other +// subtle differences between arrow functions and regular functions that you will learn about at a much later stage). +var numbersTimes400 = numbers.map(arr => { + return arr * 400; +}); +console.log(numbersTimes400); + + +// There is one last thing you can do to make your code shorter. If you remove the braces (`{}`) from an arrow +// function, the body of the function will be returned without needing to write the `return` keyword. +var numbersTimes500 = numbers.map(arr => arr * 500); +console.log(numbersTimes500); + +// In the example above, the expression `arr * 500` is automatically returned because it comes directly after +// the `=>` arrow (instead of coming after curly braces). This is called an `implicit return`. diff --git a/week-3/1-exercises/F-array-forEach/exercise.js b/week-3/1-exercises/F-array-forEach/exercise.js index e83e2df..cb5b498 100644 --- a/week-3/1-exercises/F-array-forEach/exercise.js +++ b/week-3/1-exercises/F-array-forEach/exercise.js @@ -9,6 +9,22 @@ var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; +function printFizzBuzz(arr) { + if (arr % 3 === 0 && arr % 5 === 0) { + return "FizzBuzz"; + } else if (arr % 3 === 0) { + return "Fizz"; + } else if (arr % 5 === 0) { + return "Buzz"; + } else { + return arr; + } +} + +var arrFizzBuzz = arr.map(printFizzBuzz).forEach(function(arr) { + console.log(arr); +}); + /* EXPECTED OUTPUT */ /* diff --git a/week-3/1-exercises/G-array-methods/exercise.js b/week-3/1-exercises/G-array-methods/exercise.js index 44e9c80..6a8e4b3 100644 --- a/week-3/1-exercises/G-array-methods/exercise.js +++ b/week-3/1-exercises/G-array-methods/exercise.js @@ -4,7 +4,7 @@ */ var numbers = [3, 2, 1]; -var sortedNumbers; // complete this statement +var sortedNumbers = numbers.sort(); // complete this statement /* DO NOT EDIT BELOW THIS LINE diff --git a/week-3/1-exercises/G-array-methods/exercise2.js b/week-3/1-exercises/G-array-methods/exercise2.js index 3dd24a1..dd87089 100644 --- a/week-3/1-exercises/G-array-methods/exercise2.js +++ b/week-3/1-exercises/G-array-methods/exercise2.js @@ -7,7 +7,7 @@ var mentors = ["Daniel", "Irina", "Rares"]; var students = ["Rukmini", "Abdul", "Austine", "Swathi"]; -var everyone; // complete this statement +var everyone = mentors.concat(students); // complete this statement /* DO NOT EDIT BELOW THIS LINE diff --git a/week-3/1-exercises/H-array-methods-2/exercise.js b/week-3/1-exercises/H-array-methods-2/exercise.js index d36303b..3aa962b 100644 --- a/week-3/1-exercises/H-array-methods-2/exercise.js +++ b/week-3/1-exercises/H-array-methods-2/exercise.js @@ -15,8 +15,8 @@ var everyone = [ "Swathi" ]; -var firstFive; // complete this statement -var lastFive; // complete this statement +var firstFive = everyone.slice(0, 5); // complete this statement +var lastFive = everyone.slice(-5); // complete this statement /* DO NOT EDIT BELOW THIS LINE diff --git a/week-3/1-exercises/H-array-methods-2/exercise2.js b/week-3/1-exercises/H-array-methods-2/exercise2.js index b7be576..775d911 100644 --- a/week-3/1-exercises/H-array-methods-2/exercise2.js +++ b/week-3/1-exercises/H-array-methods-2/exercise2.js @@ -6,7 +6,9 @@ For example, capitailise("hello") should return "Hello" Tip: use the string method .split() and the array method .join() */ - +// https://www.freecodecamp.org/news/how-to-capitalize-the-first-letter-of-a-string-in-javascript/ +// https://stackoverflow.com/questions/9823718/replace-forward-slash-character-in-javascript-string/9823754#:~:text=To%20escape%20them%2C%20put%20a,%5C%20)%20in%20front%20of%20it.&text=Remove%20all%20forward%20slash%20occurrences%20with%20blank%20char%20in%20Javascript%20.&text=You%20can%20just%20replace%20like,03%2F2012%22%3B%20someString. +// my_string.split('/').join('replace_with_this') function capitalise(str) {} /* diff --git a/week-3/1-exercises/H-array-methods-2/exercise3.js b/week-3/1-exercises/H-array-methods-2/exercise3.js index 82e9dd8..75a6b76 100644 --- a/week-3/1-exercises/H-array-methods-2/exercise3.js +++ b/week-3/1-exercises/H-array-methods-2/exercise3.js @@ -7,7 +7,7 @@ var ukNations = ["Scotland", "Wales", "England", "Northern Ireland"]; function isInUK(country) { - return; // complete this statement + return ukNations.includes(country); // complete this statement } /* diff --git a/week-3/2-mandatory/1-oxygen-levels.js b/week-3/2-mandatory/1-oxygen-levels.js index 3c02135..1758c1e 100644 --- a/week-3/2-mandatory/1-oxygen-levels.js +++ b/week-3/2-mandatory/1-oxygen-levels.js @@ -9,8 +9,9 @@ To be safe, they need to land on the first unamed planet that has Oxygen levels Write a function that finds the oxygen level of the first safe planet - Oxygen between 19.5% and 23.5% */ -function safeLevels() { - +function safeLevels(o2) { + let o2 = o2.replace("%", ""); + return o2 >= 19.5 && o2 <= 23.5; } /* ======= TESTS - DO NOT MODIFY ===== */ From 7618a53eef3b54ec22c645343570bf143fe88735 Mon Sep 17 00:00:00 2001 From: wonder woman Date: Wed, 1 Jul 2020 06:15:09 +0100 Subject: [PATCH 14/18] Completed mandatory Q1 & Q2 --- week-3/1-exercises/D-array-filter/exercise.js | 2 +- week-3/2-mandatory/1-oxygen-levels.js | 15 ++++++++++++--- week-3/2-mandatory/2-bush-berries.js | 17 +++++++++++++++-- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/week-3/1-exercises/D-array-filter/exercise.js b/week-3/1-exercises/D-array-filter/exercise.js index 6e32cc6..e6c30b1 100644 --- a/week-3/1-exercises/D-array-filter/exercise.js +++ b/week-3/1-exercises/D-array-filter/exercise.js @@ -8,7 +8,7 @@ var pairsByIndexRaw = [[0, 3], [1, 2], [2, 1], null, [1], false, "whoops"]; -var pairsByIndex; // Complete this statement +var pairsByIndex = pairsByIndexRaw.filter(function(indexes)); // Complete this statement var students = ["Islam", "Lesley", "Harun", "Rukmini"]; var mentors = ["Daniel", "Irina", "Mozafar", "Luke"]; diff --git a/week-3/2-mandatory/1-oxygen-levels.js b/week-3/2-mandatory/1-oxygen-levels.js index 1758c1e..0828911 100644 --- a/week-3/2-mandatory/1-oxygen-levels.js +++ b/week-3/2-mandatory/1-oxygen-levels.js @@ -9,9 +9,18 @@ To be safe, they need to land on the first unamed planet that has Oxygen levels Write a function that finds the oxygen level of the first safe planet - Oxygen between 19.5% and 23.5% */ -function safeLevels(o2) { - let o2 = o2.replace("%", ""); - return o2 >= 19.5 && o2 <= 23.5; +function findRightPlanet(oxygenLevelOfPlanet) { + if (parseFloat(oxygenLevelOfPlanet) > `${19.5}%` && parseFloat(oxygenLevelOfPlanet) < `${23.5}%`) { + return `${oxygenLevelOfPlanet}%`; + } else { + return; // it will not do anything if you write return on its own + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find +// find the first element that meets the condition and ends the test (different from filter) +function safeLevels(oxygenLevel) { + return oxygenLevel.find(findRightPlanet) } /* ======= TESTS - DO NOT MODIFY ===== */ diff --git a/week-3/2-mandatory/2-bush-berries.js b/week-3/2-mandatory/2-bush-berries.js index d900323..0420264 100644 --- a/week-3/2-mandatory/2-bush-berries.js +++ b/week-3/2-mandatory/2-bush-berries.js @@ -9,9 +9,22 @@ Use the tests to confirm which message to return */ +// check one berry colour is pink === true +function checkColourPink(berryColour) { + if(berryColour === 'pink') { + return true; + } +} -function bushChecker() { - +// check all berry colours are pink === true +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every +function bushChecker(allBushBerryColours) { + let colourResult = allBushBerryColours.every(checkColourPink); + if(colourResult === true) { + return "Bush is safe to eat from"; + } else { + return "Toxic! Leave bush alone!"; + } } /* ======= TESTS - DO NOT MODIFY ===== */ From 1444144048176e9011f539bff14db9120259d1e8 Mon Sep 17 00:00:00 2001 From: wonder woman Date: Thu, 2 Jul 2020 13:33:27 +0100 Subject: [PATCH 15/18] Completed wk3 Mandatory Q1 - Q3 --- week-3/2-mandatory/1-oxygen-levels.js | 16 ++++++++++++++-- week-3/2-mandatory/2-bush-berries.js | 7 +++++++ week-3/2-mandatory/3-space-colonies.js | 14 +++++++++++++- week-3/2-mandatory/6-lane-names.js | 15 ++++++++++++++- week-3/2-mandatory/7-password-validator.js | 4 ++-- 5 files changed, 50 insertions(+), 6 deletions(-) diff --git a/week-3/2-mandatory/1-oxygen-levels.js b/week-3/2-mandatory/1-oxygen-levels.js index 0828911..cdc09f9 100644 --- a/week-3/2-mandatory/1-oxygen-levels.js +++ b/week-3/2-mandatory/1-oxygen-levels.js @@ -9,6 +9,13 @@ To be safe, they need to land on the first unamed planet that has Oxygen levels Write a function that finds the oxygen level of the first safe planet - Oxygen between 19.5% and 23.5% */ +/* NOTES +filter() gives you a new array +include() gives you a boolean +every() gives you a boolean +find() gives you the first value that meets the condition(s) +*/ + function findRightPlanet(oxygenLevelOfPlanet) { if (parseFloat(oxygenLevelOfPlanet) > `${19.5}%` && parseFloat(oxygenLevelOfPlanet) < `${23.5}%`) { return `${oxygenLevelOfPlanet}%`; @@ -18,9 +25,14 @@ function findRightPlanet(oxygenLevelOfPlanet) { } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find -// find the first element that meets the condition and ends the test (different from filter) +// find the first element that meets the condition and ends the test (different from filter which gives you a new array) function safeLevels(oxygenLevel) { - return oxygenLevel.find(findRightPlanet) + return oxygenLevel.find(findRightPlanet); +} + +// EK's version - passed +function safeLevels(oxygen) { + return oxygen.find(level => level > "19.5%" && level < "23.5%"); } /* ======= TESTS - DO NOT MODIFY ===== */ diff --git a/week-3/2-mandatory/2-bush-berries.js b/week-3/2-mandatory/2-bush-berries.js index 0420264..8db3541 100644 --- a/week-3/2-mandatory/2-bush-berries.js +++ b/week-3/2-mandatory/2-bush-berries.js @@ -27,6 +27,13 @@ function bushChecker(allBushBerryColours) { } } +// EK's version - .some function finds if any element is not 'pink' +function bushChecker(berry) { + if (berry.some(color => color !== 'pink')) { + return "Toxic! Leave bush alone!"; + } 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 f99891a..0fc47a5 100644 --- a/week-3/2-mandatory/3-space-colonies.js +++ b/week-3/2-mandatory/3-space-colonies.js @@ -8,8 +8,20 @@ NOTE: don't include any element that is not a "family". */ -function colonisers() { +// find elements that include "family" and starts with an "A" +/* my version failed +function colonisers(name) { + if (name.includes('family') && name.startsWith('A')) { + return name; + } +} + +console.log(name.filter(colonisers)); +*/ +// EK's version modified +function colonisers(voyagersArr) { + return voyagersArr.filter(voyager => voyager.includes('family') && voyager[0] === 'A'); } /* ======= TESTS - DO NOT MODIFY ===== */ diff --git a/week-3/2-mandatory/6-lane-names.js b/week-3/2-mandatory/6-lane-names.js index eddfe44..cb3409a 100644 --- a/week-3/2-mandatory/6-lane-names.js +++ b/week-3/2-mandatory/6-lane-names.js @@ -4,8 +4,21 @@ Write a function that will return all street names which contain 'Lane' in their name. */ -function getLanes() { +// https://www.youtube.com/watch?v=iOml7u_sAVk +const streetNames = [ + "Abchurch Lane", + "Adam's Court", + "Addle Hill", + "Addle Lane", + "Alban Highwalk" +] + +function getLanes(streetNames) { + let result = streetNames.includes('Lane'); // returns boolean + if (result === true) { + return streetNames; + } } /* ======= TESTS - DO NOT MODIFY ===== */ diff --git a/week-3/2-mandatory/7-password-validator.js b/week-3/2-mandatory/7-password-validator.js index 57b3d53..0502763 100644 --- a/week-3/2-mandatory/7-password-validator.js +++ b/week-3/2-mandatory/7-password-validator.js @@ -21,9 +21,9 @@ Expected Result: PasswordValidationResult= [false, false, false, false, true] */ - +// https://stackoverflow.com/questions/36097097/password-validate-8-digits-contains-upper-lowercase-and-a-special-character function validatePasswords(passwords) { - +passwords.length >=5; } /* ======= TESTS - DO NOT MODIFY ===== */ From 3e0563b31a7318d4250ee4db5fe36103916bdc4d Mon Sep 17 00:00:00 2001 From: wonder woman Date: Thu, 2 Jul 2020 20:19:02 +0100 Subject: [PATCH 16/18] Completed mandatory Q4 & Q5 --- week-3/2-mandatory/4-eligible-students.js | 21 +++++++++++++++------ week-3/2-mandatory/5-journey-planner.js | 10 ++++++++-- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/week-3/2-mandatory/4-eligible-students.js b/week-3/2-mandatory/4-eligible-students.js index 6424b01..6b7a4fb 100644 --- a/week-3/2-mandatory/4-eligible-students.js +++ b/week-3/2-mandatory/4-eligible-students.js @@ -7,9 +7,18 @@ - Returns an array containing only the names of the who have attended AT LEAST 8 classes */ -function eligibleStudents() { - +function eligibleStudents(arr) { + let newArr = []; + for (let i = 0; i < arr.length; i++) { + for (let j = 0; j < arr[i].length; j++) { + if (arr[i][j] >= 8) { + newArr.push(arr[i][0]); + } + } + } return newArr; } +//console.log(newArr); +//console.log(eligibleStudents(attendances)); /* ======= TESTS - DO NOT MODIFY ===== */ @@ -26,11 +35,11 @@ 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; } @@ -41,7 +50,7 @@ function test(test_name, expr) { } else { status = "FAILED"; } - + console.log(`${test_name}: ${status}`); } @@ -49,4 +58,4 @@ test("eligibleStudents function works", arraysEqual( eligibleStudents(attendances), ["Ahmed", "Clement", "Tayoa", "Nina"] ) -) \ No newline at end of file +) diff --git a/week-3/2-mandatory/5-journey-planner.js b/week-3/2-mandatory/5-journey-planner.js index 53499c3..89ff128 100644 --- a/week-3/2-mandatory/5-journey-planner.js +++ b/week-3/2-mandatory/5-journey-planner.js @@ -7,8 +7,14 @@ NOTE: only the names should be returned, not the means of transport. */ -function journeyPlanner() { - +function journeyPlanner(locationsArr, transport) { + let newArr = []; + for(let i = 0; i < locationsArr.length; i++) { + if (locationsArr[i].includes(transport)) { + newArr.push(locationsArr[i][0]); + } + } + return newArr; } /* ======= TESTS - DO NOT MODIFY ===== */ From 53ed96cc48c93996dee830a1c1e79b93b39b77bd Mon Sep 17 00:00:00 2001 From: wonder woman Date: Thu, 2 Jul 2020 20:27:15 +0100 Subject: [PATCH 17/18] Completed Mandatory Q6 Lane Names --- week-3/2-mandatory/6-lane-names.js | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/week-3/2-mandatory/6-lane-names.js b/week-3/2-mandatory/6-lane-names.js index cb3409a..e121956 100644 --- a/week-3/2-mandatory/6-lane-names.js +++ b/week-3/2-mandatory/6-lane-names.js @@ -5,20 +5,15 @@ */ // https://www.youtube.com/watch?v=iOml7u_sAVk -const streetNames = [ - "Abchurch Lane", - "Adam's Court", - "Addle Hill", - "Addle Lane", - "Alban Highwalk" -] function getLanes(streetNames) { - let result = streetNames.includes('Lane'); // returns boolean - - if (result === true) { - return streetNames; + let newArr = []; + for (let i = 0; i < streetNames.length; i++) { + if (streetNames[i].includes("Lane")) { + newArr.push(streetNames[i]); + } } + return newArr; } /* ======= TESTS - DO NOT MODIFY ===== */ From b25c3a17bbeee82e86711d4996adb154b2f98cf2 Mon Sep 17 00:00:00 2001 From: wonder woman Date: Mon, 6 Jul 2020 16:22:14 +0100 Subject: [PATCH 18/18] Completed Q7 password, and half-way through Q8 codewars --- week-3/2-mandatory/5-journey-planner.js | 18 +++++++ week-3/2-mandatory/7-password-validator.js | 40 +++++++++++++- week-3/2-mandatory/7.b- password.js | 40 ++++++++++++++ week-3/2-mandatory/8-codewars.md | 62 ++++++++++++++++++++++ 4 files changed, 159 insertions(+), 1 deletion(-) create mode 100644 week-3/2-mandatory/7.b- password.js diff --git a/week-3/2-mandatory/5-journey-planner.js b/week-3/2-mandatory/5-journey-planner.js index 89ff128..a5cc39f 100644 --- a/week-3/2-mandatory/5-journey-planner.js +++ b/week-3/2-mandatory/5-journey-planner.js @@ -17,6 +17,24 @@ function journeyPlanner(locationsArr, transport) { return newArr; } +// SA's version +/* +function journeyPlanner(arr, transportMode) { + let matchedResult = []; + let res = arr.map(b => b.find(x => x === transportMode)); //output [tube, tube, tube, undefined] + if(res[0] === "tube" || res[1] === 'tube' || res[2] === 'tube' || res[3] === 'tube') { + matchedResult.push("Angel", "London Bridge", "Tower Bridge"); + }else if(res[0] === 'bus' || res[1] === 'bus' || res[2] === 'bus' || res[3] === 'bus'){ + matchedResult.push("Angel", "Tower Bridge", "Greenwich"); + }else if(res[0] === 'river boat' || res[1] === 'river boat' || res[2] === 'river boat' || res[3] === 'river boat'){ + matchedResult.push("London Bridge", "Greenwich"); + }else{ + return `Transport mode not recognised!`; + } + return matchedResult; +} +*/ + /* ======= TESTS - DO NOT MODIFY ===== */ const londonLocations = [ diff --git a/week-3/2-mandatory/7-password-validator.js b/week-3/2-mandatory/7-password-validator.js index 0502763..978be03 100644 --- a/week-3/2-mandatory/7-password-validator.js +++ b/week-3/2-mandatory/7-password-validator.js @@ -22,8 +22,46 @@ PasswordValidationResult= [false, false, false, false, true] */ // https://stackoverflow.com/questions/36097097/password-validate-8-digits-contains-upper-lowercase-and-a-special-character +// https://www.geeksforgeeks.org/validate-a-password-using-html-and-javascript/ +/* my version - BUG +function validatePasswords(passwordsArr) { + let result = []; + for(let i = 0; i < passwordsArr; i++) { + if (passwordsArr[i].match(/[a-z]/g) && + passwardsArr[i].match(/[A-Z]/g) && + passwordsArr[i].match(/[0-9]/g) && + passwordsArr[i].match(/[^a-zA-Z\w]/g) && + //passwordsArr[i].match([\u0021-\u007E]/g) && // This checks all of the non alphanumeric characters. + passwordsArr[i].match(/^[!#$%.]+$) && // ^ and $ means from the start to the end of the password + passwordsArr[i].length >= 5) { + result.push(true); + } else { + result.push(false); + } + } return result; +} + +console.log(validatePasswords(passwords2)) +*/ + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions +// GG's version function validatePasswords(passwords) { -passwords.length >=5; + const lowerCase = /[a-z]/; + const upperCase = /[A-Z]/; + const numbers = /[0-9]/; + const nonAlphanum = /[!#\$%\.\*&]/; + let areValid = []; + for (let i = 0; i < passwords.length; ++i) { + areValid.push( + lowerCase.test(passwords[i]) && + upperCase.test(passwords[i]) && + numbers.test(passwords[i]) && + nonAlphanum.test(passwords[i]) && + passwords[i].length >= 5 && + passwords.indexOf(passwords[i]) === i); + } + return areValid; } /* ======= TESTS - DO NOT MODIFY ===== */ diff --git a/week-3/2-mandatory/7.b- password.js b/week-3/2-mandatory/7.b- password.js new file mode 100644 index 0000000..25990df --- /dev/null +++ b/week-3/2-mandatory/7.b- password.js @@ -0,0 +1,40 @@ +const passwords2 = ["StUFf27%", "Pl3nty!", "Jai33", "shajsaUA**&&", "Pl3nty!"] + +function validatePasswords(arr) { + let bigArrayOfChar = arr.map(element => element.split('')); //map returns a new array + let result1 = bigArrayOfChar.map(index => index.some(isNum) && index.some(isUpperCase) && index.some(isLowerCase)); + let result2 = arr.map(fiveChar); + return result1 && result2; +} + +function isNum(word) { + let newWord = word.split(''); + let checkLetter = newWord.some(element => element >= 0 && element <= 9); //some returns boolean + return checkLetter; +} + +function isUpperCase(word) { + let newWord = word.split(''); + let checkUpperCase = newWord.some(element => element >= 'A' && element <= 'Z'); + return checkUpperCase; +} + +function isLowerCase(word) { + let newWord = word.split(''); + let checkLowerCase = newWord.some(element => element >= 'a' && element <= 'z'); + return checkLowerCase; +} + +function fiveChar(word) { + let newWord = word.length >= 5; + return newWord; +} + +function hasSymbols(word) { + //let newWord = word.includes("!").includes(, "#", "$", "%", ".")); + let regex = /[!#$%.*&]/; + return regex.test(word); +} + +console.log(validatePasswords(passwords2)); +//console.log(isNum(passwords2); \ No newline at end of file diff --git a/week-3/2-mandatory/8-codewars.md b/week-3/2-mandatory/8-codewars.md index 8bd2b85..0eab605 100644 --- a/week-3/2-mandatory/8-codewars.md +++ b/week-3/2-mandatory/8-codewars.md @@ -9,22 +9,84 @@ Today, you'll be using a platform called [CodeWars](https://codewars.com) to hel *Functions, types, conditionals etc...* - [even or odd](https://www.codewars.com/kata/even-or-odd/train/javascript) +function even_or_odd(number) { + if (number % 2 === 0) { + return "Even"; + } return "Odd"; +} + - [code under pressure](https://www.codewars.com/kata/you-cant-code-under-pressure-number-1/train/javascript) +function doubleInteger(i) { + i = i * 2; + return i; +} + - [secret message](https://www.codewars.com/kata/jennys-secret-message/train/javascript) +function greet(name){ + if(name === "Johnny") { + return "Hello, my love!"; + } return "Hello, " + name + "!"; +} + - [convert boolean](https://www.codewars.com/kata/convert-boolean-values-to-strings-yes-or-no/train/javascript) +function boolToWord( bool ){ + if (bool === true) { + return 'Yes'; + } return 'No'; +} + - [opposite number](https://www.codewars.com/kata/opposite-number/train/javascript) +function opposite(number) { + return number * -1; +} + - [return negative](https://www.codewars.com/kata/return-negative/train/javascript) +function makeNegative(num) { + if (num < 0) { + return num; + } return num * -1; +} + - [hydrated](https://www.codewars.com/kata/keep-hydrated-1/train/javascript) +function litres(time) { + let litres = Math.floor(time) * .5; + return Math.floor(litres); +} + - [bonus](https://www.codewars.com/kata/do-i-get-a-bonus/train/javascript) +function bonusTime(salary, bonus) { + if (bonus === false) { + return `£${salary}`; + } return `£${salary * 10}`; +} + - [remove string spaces](https://www.codewars.com/kata/remove-string-spaces/train/javascript) +function noSpace(x){ + return x.replace(/\s/g, ''); +} + - [remove first and last character](https://www.codewars.com/kata/remove-first-and-last-character/train/javascript) +function removeChar(str){ + str = str.slice(1, -1); + return str +}; + - [string repeat](https://www.codewars.com/kata/string-repeat/train/javascript) +function repeatStr (n, s) { + s = s.repeat(n); + return s; +} + - [mathematical operations](https://www.codewars.com/kata/basic-mathematical-operations/train/javascript) *Arrays* - [invert values](https://www.codewars.com/kata/invert-values/train/javascript) - [needle in haystack](https://www.codewars.com/kata/a-needle-in-the-haystack/train/javascript) +function findNeedle(haystack) { + return `found the needle at position ${haystack.indexOf('needle')}`; +} + - [counting sheep](https://www.codewars.com/kata/counting-sheep-dot-dot-dot/train/javascript) - [sum of positive](https://www.codewars.com/kata/sum-of-positive/train/javascript) - [people in bus](https://www.codewars.com/kata/number-of-people-in-the-bus/train/javascript)