From 9834fd2193ad5b6b7ceb77c43d5c05dd919d35ff Mon Sep 17 00:00:00 2001 From: mr_maroga <45645052+AdvocateM@users.noreply.github.com> Date: Wed, 29 Jun 2022 05:28:35 +0200 Subject: [PATCH 1/8] Add files via upload --- exercises/B-hello-world/exercise.js | 4 +++- exercises/C-variables/exercise.js | 4 +++- exercises/D-strings/exercise.js | 3 +++ exercises/E-strings-concatenation/exercise.js | 6 +++++- exercises/F-strings-methods/exercise.js | 7 +++++++ exercises/F-strings-methods/exercise2.js | 2 ++ exercises/G-numbers/exercise.js | 6 ++++++ exercises/I-floats/exercise.js | 9 +++++++++ exercises/J-functions/exercise.js | 1 + exercises/J-functions/exercise2.js | 1 + exercises/K-functions-parameters/exercise.js | 3 ++- exercises/K-functions-parameters/exercise2.js | 3 +++ exercises/K-functions-parameters/exercise3.js | 6 +++++- exercises/K-functions-parameters/exercise4.js | 4 ++++ exercises/K-functions-parameters/exercise5.js | 5 ++++- exercises/L-functions-nested/exercise.js | 14 ++++++++++++++ 16 files changed, 72 insertions(+), 6 deletions(-) diff --git a/exercises/B-hello-world/exercise.js b/exercises/B-hello-world/exercise.js index b179ee953..9fb7c7a52 100644 --- a/exercises/B-hello-world/exercise.js +++ b/exercises/B-hello-world/exercise.js @@ -1 +1,3 @@ -console.log("Hello world"); +console.log( + "Hello world i just started Learning Javascript home you welcome me" +); diff --git a/exercises/C-variables/exercise.js b/exercises/C-variables/exercise.js index a6bbb9786..e3ca1c1ec 100644 --- a/exercises/C-variables/exercise.js +++ b/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); \ No newline at end of file diff --git a/exercises/D-strings/exercise.js b/exercises/D-strings/exercise.js index 2cffa6a81..3772ea23d 100644 --- a/exercises/D-strings/exercise.js +++ b/exercises/D-strings/exercise.js @@ -1,3 +1,6 @@ // 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/exercises/E-strings-concatenation/exercise.js b/exercises/E-strings-concatenation/exercise.js index 2cffa6a81..0d0bb1d05 100644 --- a/exercises/E-strings-concatenation/exercise.js +++ b/exercises/E-strings-concatenation/exercise.js @@ -1,3 +1,7 @@ // Start by creating a variable `message` +var greetings = "Hello, my name is "; +var nameD = "Daniel"; -console.log(message); +var message = greetings + nameD; + +var message = console.log(message); diff --git a/exercises/F-strings-methods/exercise.js b/exercises/F-strings-methods/exercise.js index 2cffa6a81..20f836c58 100644 --- a/exercises/F-strings-methods/exercise.js +++ b/exercises/F-strings-methods/exercise.js @@ -1,3 +1,10 @@ // Start by creating a variable `message` +var names = "Daniel"; +var intro = "My name is "; +// second part +var intro2 = "my name is "; +var characterMessage = "characters long"; + +message = intro + names + " and " + intro2 + names.length + characterMessage; console.log(message); diff --git a/exercises/F-strings-methods/exercise2.js b/exercises/F-strings-methods/exercise2.js index b4b46943d..5fa428eca 100644 --- a/exercises/F-strings-methods/exercise2.js +++ b/exercises/F-strings-methods/exercise2.js @@ -1,3 +1,5 @@ const name = " Daniel "; +const message = name.trim(); + console.log(message); diff --git a/exercises/G-numbers/exercise.js b/exercises/G-numbers/exercise.js index 49e7bc00b..c1040fd49 100644 --- a/exercises/G-numbers/exercise.js +++ b/exercises/G-numbers/exercise.js @@ -1 +1,7 @@ // Start by creating a variables `numberOfStudents` and `numberOfMentors` +var numberOfStudents = 15; +var numberOfMentors = 8; + +var total = numberOfStudents + numberOfMentors; + +console.log(total); diff --git a/exercises/I-floats/exercise.js b/exercises/I-floats/exercise.js index a5bbcd852..986f0fab7 100644 --- a/exercises/I-floats/exercise.js +++ b/exercises/I-floats/exercise.js @@ -1,2 +1,11 @@ var numberOfStudents = 15; var numberOfMentors = 8; + +const students = ; +const mentor = (15 - 8) / 15; + +const studentPercent = Math.round(students); +const mentorPercent = Math.round(mentor); + +console.log(mentorPercent); +console.log(mentorPercent); diff --git a/exercises/J-functions/exercise.js b/exercises/J-functions/exercise.js index 0ae5850e5..d568c193f 100644 --- a/exercises/J-functions/exercise.js +++ b/exercises/J-functions/exercise.js @@ -1,5 +1,6 @@ function halve(number) { // complete the function here + return number - 6; } var result = halve(12); diff --git a/exercises/J-functions/exercise2.js b/exercises/J-functions/exercise2.js index 82ef5e780..468d45596 100644 --- a/exercises/J-functions/exercise2.js +++ b/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/exercises/K-functions-parameters/exercise.js b/exercises/K-functions-parameters/exercise.js index 8d5db5e69..dbd50454d 100644 --- a/exercises/K-functions-parameters/exercise.js +++ b/exercises/K-functions-parameters/exercise.js @@ -1,6 +1,7 @@ // Complete the function so that it takes input parameters -function multiply() { +function multiply(a, b) { // Calculate the result of the function and return it + return a * b; } // Assign the result of calling the function the variable `result` diff --git a/exercises/K-functions-parameters/exercise2.js b/exercises/K-functions-parameters/exercise2.js index db7a8904b..ab4102430 100644 --- a/exercises/K-functions-parameters/exercise2.js +++ b/exercises/K-functions-parameters/exercise2.js @@ -1,4 +1,7 @@ // Declare your function first +function divide(a, b) { + return a / b; +} var result = divide(3, 4); diff --git a/exercises/K-functions-parameters/exercise3.js b/exercises/K-functions-parameters/exercise3.js index 537e9f4ec..98e2aa39a 100644 --- a/exercises/K-functions-parameters/exercise3.js +++ b/exercises/K-functions-parameters/exercise3.js @@ -1,5 +1,9 @@ // Write your function here +function createGreeting(greetings, name) { + greetings = "Hello, my name is "; + return greetings + name; +} -var greeting = createGreeting("Daniel"); +var greeting = createGreeting(greeting, "Daniel"); console.log(greeting); diff --git a/exercises/K-functions-parameters/exercise4.js b/exercises/K-functions-parameters/exercise4.js index 7ab44589e..6d899e5d9 100644 --- a/exercises/K-functions-parameters/exercise4.js +++ b/exercises/K-functions-parameters/exercise4.js @@ -1,5 +1,9 @@ // Declare your function first +function sum(number1, number2) { + return number1 + number2; +} // Call the function and assign to a variable `sum` +var sum = sum(13, 124); console.log(sum); diff --git a/exercises/K-functions-parameters/exercise5.js b/exercises/K-functions-parameters/exercise5.js index 7c5bcd605..a5b5aa121 100644 --- a/exercises/K-functions-parameters/exercise5.js +++ b/exercises/K-functions-parameters/exercise5.js @@ -1,5 +1,8 @@ // Declare your function here +function createGreeting(name, age) { + return `Hello, my name is ${name} and I'm ${age} years old`; +} -const greeting = createLongGreeting("Daniel", 30); +const greeting = createLongGreeting("Daniel ", 30); console.log(greeting); diff --git a/exercises/L-functions-nested/exercise.js b/exercises/L-functions-nested/exercise.js index a5d377442..894dc6124 100644 --- a/exercises/L-functions-nested/exercise.js +++ b/exercises/L-functions-nested/exercise.js @@ -3,3 +3,17 @@ var mentor2 = "Irina"; var mentor3 = "Mimi"; var mentor4 = "Rob"; var mentor5 = "Yohannes"; + +function uppCase(name) { + return name.toUpperCase(); +} +function greeting(name) { + let shoutyName = uppCase(name); + let message = "HELLO " + shoutyName; + return message; +} +console.log(greeting(mentor1)); +console.log(greeting(mentor2)); +console.log(greeting(mentor3)); +console.log(greeting(mentor4)); +console.log(greeting(mentor5)); \ No newline at end of file From dcac6859a313321805032f23b9055e53aff4d77d Mon Sep 17 00:00:00 2001 From: mr_maroga <45645052+AdvocateM@users.noreply.github.com> Date: Wed, 29 Jun 2022 05:28:59 +0200 Subject: [PATCH 2/8] Add files via upload --- mandatory/1-syntax-errors.js | 11 ++++++----- mandatory/2-logic-error.js | 10 ++++++---- mandatory/3-function-output.js | 3 +++ mandatory/4-tax.js | 13 +++++++++++-- 4 files changed, 26 insertions(+), 11 deletions(-) diff --git a/mandatory/1-syntax-errors.js b/mandatory/1-syntax-errors.js index a10cc9ac2..98360ac6b 100644 --- a/mandatory/1-syntax-errors.js +++ b/mandatory/1-syntax-errors.js @@ -1,16 +1,17 @@ // 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 getTotal(a, b) { - total = a ++ b; + total = a + b; - return "The total is total"; + return "The total is " + total; } /* diff --git a/mandatory/2-logic-error.js b/mandatory/2-logic-error.js index 9cca7603b..ad616b61e 100644 --- a/mandatory/2-logic-error.js +++ b/mandatory/2-logic-error.js @@ -1,16 +1,18 @@ // 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(); + // return wordtrim(); } function getStringLength(word) { - return "word".length(); + // return "word".length(); + return word.length; } function multiply(a, b, c) { - a * b * c; - return; + // a * b * c; + return a * b * c; } /* diff --git a/mandatory/3-function-output.js b/mandatory/3-function-output.js index 5a953ba60..d0bdd903c 100644 --- a/mandatory/3-function-output.js +++ b/mandatory/3-function-output.js @@ -1,15 +1,18 @@ // Add comments to explain what this function does. You're meant to use Google! +// The function round Floats to the nearest whole number using the `Math.round` function function getRandomNumber() { return Math.random() * 10; } // Add comments to explain what this function does. You're meant to use Google! +// This Function concatenate(combine) two words function combine2Words(word1, word2) { return word1.concat(word2); } function concatenate(firstWord, secondWord, thirdWord) { // Write the body of this function to concatenate three words together. + return firstWord + " " + secondWord + " " + thirdWord; // Look at the test case below to understand what this function is expected to return. } diff --git a/mandatory/4-tax.js b/mandatory/4-tax.js index ba77c7ae2..2e20238d8 100644 --- a/mandatory/4-tax.js +++ b/mandatory/4-tax.js @@ -5,7 +5,11 @@ Sales tax is 20% of the price of the product. */ -function calculateSalesTax() {} +function calculateSalesTax(price) { + var percent = price * 0.2; + var totalIncludingTax = percent + price; + return totalIncludingTax; +} /* CURRENCY FORMATTING @@ -17,7 +21,12 @@ function calculateSalesTax() {} Remember that the prices must include the sales tax (hint: you already wrote a function for this!) */ -function addTaxAndFormatCurrency() {} +function addTaxAndFormatCurrency(price) { + let percentageOfPrice = price * 0.2; + let totalIncludingTax2 = price + percentageOfPrice; + let decimal = totalIncludingTax2.toFixed(2); + return "£" + decimal; +} /* =================================================== From f37ccd3ad77618d13eef8117ffa9b44a8117dcbf Mon Sep 17 00:00:00 2001 From: mr_maroga <45645052+AdvocateM@users.noreply.github.com> Date: Mon, 4 Jul 2022 01:00:30 +0200 Subject: [PATCH 3/8] Update exercise.js --- exercises/C-variables/exercise.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/exercises/C-variables/exercise.js b/exercises/C-variables/exercise.js index e3ca1c1ec..a17507f15 100644 --- a/exercises/C-variables/exercise.js +++ b/exercises/C-variables/exercise.js @@ -1,5 +1,5 @@ // Start by creating a variable `greeting` -var greeting = "Hello World"; +let greeting = "Hello World"; +console.log(greeting); console.log(greeting); console.log(greeting); -console.log(greeting); \ No newline at end of file From 019e4d4cdce39783331300f16b33e52fe3807388 Mon Sep 17 00:00:00 2001 From: mr_maroga <45645052+AdvocateM@users.noreply.github.com> Date: Mon, 4 Jul 2022 01:01:25 +0200 Subject: [PATCH 4/8] Update exercise.js --- exercises/E-strings-concatenation/exercise.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/exercises/E-strings-concatenation/exercise.js b/exercises/E-strings-concatenation/exercise.js index 0d0bb1d05..ad6c9bb8c 100644 --- a/exercises/E-strings-concatenation/exercise.js +++ b/exercises/E-strings-concatenation/exercise.js @@ -2,6 +2,6 @@ var greetings = "Hello, my name is "; var nameD = "Daniel"; -var message = greetings + nameD; +let message = greetings + nameD; -var message = console.log(message); +console.log(message); From 3e96c8857399c166d585e0b9133e23c8e3a2b83d Mon Sep 17 00:00:00 2001 From: mr_maroga <45645052+AdvocateM@users.noreply.github.com> Date: Mon, 4 Jul 2022 01:02:42 +0200 Subject: [PATCH 5/8] Update exercise.js --- exercises/I-floats/exercise.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/exercises/I-floats/exercise.js b/exercises/I-floats/exercise.js index 986f0fab7..6bf09b86b 100644 --- a/exercises/I-floats/exercise.js +++ b/exercises/I-floats/exercise.js @@ -4,8 +4,8 @@ var numberOfMentors = 8; const students = ; const mentor = (15 - 8) / 15; -const studentPercent = Math.round(students); -const mentorPercent = Math.round(mentor); +const studentPercent = Math.random(students); +const mentorPercent = Math.random(mentor); console.log(mentorPercent); console.log(mentorPercent); From f6eb0075a8715efeb611d0d20a2943347f857f49 Mon Sep 17 00:00:00 2001 From: mr_maroga <45645052+AdvocateM@users.noreply.github.com> Date: Mon, 4 Jul 2022 01:08:20 +0200 Subject: [PATCH 6/8] Update exercise.js --- exercises/J-functions/exercise.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/exercises/J-functions/exercise.js b/exercises/J-functions/exercise.js index d568c193f..da960ce46 100644 --- a/exercises/J-functions/exercise.js +++ b/exercises/J-functions/exercise.js @@ -3,6 +3,5 @@ function halve(number) { return number - 6; } -var result = halve(12); -console.log(result); +console.log(halve(12)); From 3cfb22e90771bd524cf256c98d54ee05f8af5a21 Mon Sep 17 00:00:00 2001 From: mr_maroga <45645052+AdvocateM@users.noreply.github.com> Date: Mon, 4 Jul 2022 01:29:52 +0200 Subject: [PATCH 7/8] Update exercise.js --- exercises/I-floats/exercise.js | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/exercises/I-floats/exercise.js b/exercises/I-floats/exercise.js index 6bf09b86b..63907dbf7 100644 --- a/exercises/I-floats/exercise.js +++ b/exercises/I-floats/exercise.js @@ -1,11 +1,12 @@ -var numberOfStudents = 15; -var numberOfMentors = 8; +let numberOfStudents = 15; +let numberOfMentors = 8; -const students = ; -const mentor = (15 - 8) / 15; +function percent(x) { + return Math.round((x / (numberOfMentors + numberOfStudents)) * 100); +} -const studentPercent = Math.random(students); -const mentorPercent = Math.random(mentor); +let studentMessage = "Percentage students:"; +let mentorMessage = "Percentage mentors:"; -console.log(mentorPercent); -console.log(mentorPercent); +console.log(mentorMessage, percent(numberOfStudents) + "%"); +console.log(studentMessage, percent(numberOfMentors) + "%"); From 3dad6c7c96f9c3f40e34c55f323dfad7d64ed7cb Mon Sep 17 00:00:00 2001 From: mr_maroga <45645052+AdvocateM@users.noreply.github.com> Date: Tue, 5 Jul 2022 11:35:59 +0200 Subject: [PATCH 8/8] Add files via upload --- CODE_STYLE.md | 1 + README.md | 30 ++----- exercises/A-expressions/README.md | 66 ++++++++++++++ exercises/B-boolean-literals/README.md | 9 ++ exercises/B-boolean-literals/exercise.js | 29 +++++++ exercises/C-comparison-operators/README.md | 29 +++++++ exercises/C-comparison-operators/exercise.js | 35 ++++++++ exercises/D-logical-operators/README.md | 39 +++++++++ exercises/D-logical-operators/exercise.js | 39 +++++++++ exercises/D-logical-operators/exercise2.js | 53 ++++++++++++ exercises/E-conditionals/README.md | 61 +++++++++++++ exercises/E-conditionals/exercise.js | 32 +++++++ exercises/F-predicates/README.md | 16 ++++ exercises/F-predicates/exercise.js | 39 +++++++++ exercises/G-conditionals-2/README.md | 24 ++++++ exercises/G-conditionals-2/exercise-1.js | 34 ++++++++ exercises/G-conditionals-2/exercise-2.js | 35 ++++++++ exercises/G-conditionals-2/exercise-3.js | 43 +++++++++ exercises/G-conditionals-2/exercise-4.js | 38 ++++++++ exercises/H-array-literals/README.md | 23 +++++ exercises/H-array-literals/exercise.js | 21 +++++ exercises/I-array-properties/README.md | 13 +++ exercises/I-array-properties/exercise.js | 32 +++++++ exercises/J-array-get-set/README.md | 26 ++++++ exercises/J-array-get-set/exercise.js | 31 +++++++ exercises/J-array-get-set/exercises2.js | 20 +++++ extra/1-radio-stations.js | 67 ++++++++++++++ mandatory/1-fix-functions.js | 85 ++++++++++++++++++ mandatory/2-function-creation.js | 91 ++++++++++++++++++++ mandatory/3-playing-computer.js | 42 +++++++++ package.json | 29 ++----- 31 files changed, 1088 insertions(+), 44 deletions(-) create mode 100644 CODE_STYLE.md create mode 100644 exercises/A-expressions/README.md create mode 100644 exercises/B-boolean-literals/README.md create mode 100644 exercises/B-boolean-literals/exercise.js create mode 100644 exercises/C-comparison-operators/README.md create mode 100644 exercises/C-comparison-operators/exercise.js create mode 100644 exercises/D-logical-operators/README.md create mode 100644 exercises/D-logical-operators/exercise.js create mode 100644 exercises/D-logical-operators/exercise2.js create mode 100644 exercises/E-conditionals/README.md create mode 100644 exercises/E-conditionals/exercise.js create mode 100644 exercises/F-predicates/README.md create mode 100644 exercises/F-predicates/exercise.js create mode 100644 exercises/G-conditionals-2/README.md create mode 100644 exercises/G-conditionals-2/exercise-1.js create mode 100644 exercises/G-conditionals-2/exercise-2.js create mode 100644 exercises/G-conditionals-2/exercise-3.js create mode 100644 exercises/G-conditionals-2/exercise-4.js create mode 100644 exercises/H-array-literals/README.md create mode 100644 exercises/H-array-literals/exercise.js create mode 100644 exercises/I-array-properties/README.md create mode 100644 exercises/I-array-properties/exercise.js create mode 100644 exercises/J-array-get-set/README.md create mode 100644 exercises/J-array-get-set/exercise.js create mode 100644 exercises/J-array-get-set/exercises2.js create mode 100644 extra/1-radio-stations.js create mode 100644 mandatory/1-fix-functions.js create mode 100644 mandatory/2-function-creation.js create mode 100644 mandatory/3-playing-computer.js diff --git a/CODE_STYLE.md b/CODE_STYLE.md new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/CODE_STYLE.md @@ -0,0 +1 @@ + diff --git a/README.md b/README.md index dff05d7cd..c022ce5dd 100644 --- a/README.md +++ b/README.md @@ -1,39 +1,23 @@ -# Coursework - Like learning a musical instrument, programming requires daily practise. The exercises are split into three folders: `exercises`, `mandatory` and `extra`. All homework in the `exercise` and `mandatory` section **must** be completed for homework by the following lesson. The `extra` folder contains exercises that you can complete to challenge yourself, but are not required for the following lesson. -## Running the code/tests - -The files for the mandatory/extra exercises are intended to be run as jest tests. - -- Once you have cloned the repository, run `npm install` once in the terminal to install jest (and any necessary dependencies). -- To run the tests for all mandatory/extra exercises, run `npm test` -- To run only the tests for the mandatory exercises, run `npm test -- --selectProjects mandatory` -- To run only the tests for the extra exercises, run `npm test -- --selectProjects extra` -- To run a single exercise/test (for example `mandatory/1-writer.js`), run `npm test -- --testPathPattern mandatory/1-writer.js` (Remember, you can use tab-completion to get files relative to the current directory, so m`Tab ↹`/1-`Tab ↹` will autocomplete get you the test file starting with 1-) - -For more information about tests, look here: - -https://syllabus.codeyourfuture.io/guides/intro-to-tests - -Try out variant way of running tests: - -- `npm test` -> run all mandatory and extra tests -- `npm test -- --selectProjects mandatory` -> run only mandatory tests -- `npm test -- --testPathPattern mandatory/1-syntax-errors.js` -> run single test - ## Solutions The solutions for this coursework can be found here: -https://github.com/CodeYourFuture/JavaScript-Core-1-Coursework-Week1-Solution +https://github.com/CodeYourFuture/JavaScript-Core-1-Coursework-Week2-Solution This is a **private** repository. Please request access from your Teachers, Buddy or City Coordinator after the start of your next lesson. +## Testing your work + +- Each of the *.js files in the `exercises` folder can be run from the terminal using the `node` command with the path to the file. For example, `node exercises/B-boolean-literals/exercise.js` can be run from the root of the project. +- To run the tests in the `mandatory` folder, run `npm run test` from the root of the project (after having run `npm install` once before). +- To run the tests in the `extra` folder, run `npm run extra-tests` from the root of the project (after having run `npm install` once before). + ## Instructions for submission For your homework, we'll be using [**test driven development**](https://medium.com/@adityaalifnugraha/test-driven-development-tdd-in-a-nutshell-b9e05dfe8adb) to check your answers. Test driven development (or TDD) is the practice of writing tests for your code first, and then write your code to pass those tests. This is a very useful way of writing good quality code and is used in a lot of industries. You don't have to worry about knowing how this works, but if you're curious, engage with a volunteer to find out more! :) diff --git a/exercises/A-expressions/README.md b/exercises/A-expressions/README.md new file mode 100644 index 000000000..d64169ed9 --- /dev/null +++ b/exercises/A-expressions/README.md @@ -0,0 +1,66 @@ +In JavaScript there are **expressions** and **statements**. We will use these words frequently to describe code. + +### Expression + +An expression returns a value. Sometimes we will say that an expression _evaluates to_ a value. + +The following are all examples of expressions: + +```js +1 + 1; // returns 2 +("hello"); // returns "hello" +2 * 4; // returns 8 +"hello" + "world"; // returns "helloworld" +``` + +We can take the value produced by an expression and assign it to a variable. That line of code would be called a statement. + +### Statement + +A statement is some code that performs an action. Here are some examples: + +```js +let sum = 1 + 1; // action: assigns result of `1 + 1` to variable `sum` +let greeting = "hello"; // action: assigns result of the expression "hello" to variable `greeting` +console.log(2 * 4); // action: logs the result of `2 * 4` to the console +sayGreeting(greeting); // action: calls the function `sayGreeting` with the parameter `greeting` +``` + +There are some other different types of statements that we will learn in the coming weeks. + +## Exercise + +You quickly find out the result of an expression by running node in a terminal window. + +- Open a terminal window +- Run the command `node` +- _You have now opened a node console (also called a REPL)_ +- Type an expression and press enter +- To exit the console type Ctrl+C or type the command `.exit` + +Example from inside a terminal window: + +```bash +$ node +> 1 + 2 +3 +> "hello" +'hello' +> let greeting = "hello" +undefined +> greeting +'hello' +> console.log(greeting) +hello +undefined +> .exit +$ +``` + +> 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 +- Assign some expressions to variables +- Check the value of the variables + +Further reading on using the node console: https://hackernoon.com/know-node-repl-better-dbd15bca0af6 diff --git a/exercises/B-boolean-literals/README.md b/exercises/B-boolean-literals/README.md new file mode 100644 index 000000000..e486fbd28 --- /dev/null +++ b/exercises/B-boolean-literals/README.md @@ -0,0 +1,9 @@ +There is a special data type in JavaScript known as a **boolean** value. A boolean is either `true` or `false`, and it should be written without quotes. + +```js +let codeYourFutureIsGreat = true; +``` + +## Exercise + +Head over to `exercise.js` and follow the instructions in the comments. diff --git a/exercises/B-boolean-literals/exercise.js b/exercises/B-boolean-literals/exercise.js new file mode 100644 index 000000000..89c372601 --- /dev/null +++ b/exercises/B-boolean-literals/exercise.js @@ -0,0 +1,29 @@ +/* + BOOLEAN LITERALS + ---------------- + This program needs some variables to log the expected result. + Add the required variables with the correct boolean values assigned. +*/ + +let codeYourFutureIsGreat = true; +let mozafarIsCool = false; +let calculationCorrect = true; +let moreThan10Students = false; + +/* + DO NOT EDIT BELOW THIS LINE + --------------------------- */ + +console.log("Is Code Your Future great?", codeYourFutureIsGreat); +console.log("Is Mozafar cool?", mozafarIsCool); +console.log("Does 1 + 1 = 2?", calculationCorrect); +console.log("Are there more than 10 students?", moreThan10Students); + +/* + EXPECTED RESULT + --------------- + Is Code Your Future great? true + Is Mozafar cool? false + Does 1 + 1 = 2? true + Are there more than 10 students? false +*/ diff --git a/exercises/C-comparison-operators/README.md b/exercises/C-comparison-operators/README.md new file mode 100644 index 000000000..fd602d9fe --- /dev/null +++ b/exercises/C-comparison-operators/README.md @@ -0,0 +1,29 @@ +We can also write **expressions** that return boolean values. + +Here's an expression that evaulates to a boolean. + +``` +1 > 2 +``` + +* Can you work out what value this expression evaluates to? + +The `>` symbol in the expression is a **comparison operator**. Comparison operators compare two values. This operator checks to see if the number on the left is bigger than the number on the right. + +`1` is not bigger than `2` so this expression returns `false`. + +**More comparison operators** + +``` +> greater than +< less than +<= less than or equal +>= greater than or equal +=== same value +!== not the same value +``` + +## Exercise + +* Open `exercise.js` and follow the instructions. +* Open a node console, and write some expressions that use comparison operators diff --git a/exercises/C-comparison-operators/exercise.js b/exercises/C-comparison-operators/exercise.js new file mode 100644 index 000000000..c76e432fb --- /dev/null +++ b/exercises/C-comparison-operators/exercise.js @@ -0,0 +1,35 @@ +/* + BOOLEAN WITH COMPARISON OPERATORS + --------------------------------- + Using comparison operators complete the unfinished statements. + The variables should have values that match the expected results. +*/ + +let studentCount = 16; +let mentorCount = 9; +let moreStudentsThanMentors = true; // finish this statement + +let roomMaxCapacity = 25; +let enoughSpaceInRoom = true; // finish this statement + +let personA = "Daniel"; +let personB = "Irina"; +let sameName = false; // finish this statement + +/* + DO NOT EDIT BELOW THIS LINE + --------------------------- */ +console.log("Are there more students than mentors?", moreStudentsThanMentors); +console.log( + "Is there enough space in the room for all students and mentors?", + enoughSpaceInRoom +); +console.log("Do person A and person B have the the same name?", sameName); + +/* + EXPECTED RESULT + --------------- + Are there more students than mentors? true + Is there enough space in the room for all students and mentors? true + Do person A and person B have the the same name? false +*/ diff --git a/exercises/D-logical-operators/README.md b/exercises/D-logical-operators/README.md new file mode 100644 index 000000000..bc080d4ea --- /dev/null +++ b/exercises/D-logical-operators/README.md @@ -0,0 +1,39 @@ +There are three logical operators in JavaScript: `||` (OR), `&&` (AND), `!` (NOT). + +They let you write expressions that evaluate to a boolean value. + +Suppose you want to test if a number if bigger than 3 and smaller than 10. We can write this using logical operators. + +```js +let num = 10; + +function satisfiesRequirements(num) { + if (num > 3 && num < 10) { + return true; + } + + return false; +} +``` + +We can test expressions with logical operators in a node console too: + +```sh +$ node +> let num = 10; +undefined +> num > 5 && num < 15 +true +> num < 10 || num === 10 +true +> false || true +true +> !true +false +> let greaterThan5 = num > 5 +undefined +> !greaterThan5 +false +> !(num === 10) +false +``` diff --git a/exercises/D-logical-operators/exercise.js b/exercises/D-logical-operators/exercise.js new file mode 100644 index 000000000..08beb3862 --- /dev/null +++ b/exercises/D-logical-operators/exercise.js @@ -0,0 +1,39 @@ +/* + Logical Operators + --------------------------------- + Using logical operators complete the unfinished statements. + The variables should have values that match the expected results. +*/ + +// Do not change these two statement +let htmlLevel = 8; +let cssLevel = 4; + +// Finish the statement to check whether HTML, CSS knowledge are above 5 +// (hint: use the comparison operator from before) +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 +let cssAndHtmlAbove5 = htmlLevel > 5 && cssLevel > 5; +let cssOrHtmlAbove5 = cssLevel > htmlLevel > 5 || htmlLevel > 5; + +/* + DO NOT EDIT BELOW THIS LINE + --------------------------- */ + +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); + +/* + EXPECTED RESULT + --------------- + Is Html knowledge above 5? true + Is CSS knowledge above 5? false + Is Html And CSS knowledge above 5? false + Is either Html or CSS knowledge above 5? true +*/ diff --git a/exercises/D-logical-operators/exercise2.js b/exercises/D-logical-operators/exercise2.js new file mode 100644 index 000000000..75e58fa4b --- /dev/null +++ b/exercises/D-logical-operators/exercise2.js @@ -0,0 +1,53 @@ +/* + Logical Operators + --------------------------------- + This program calls some functions that are either missing or incomplete. + Update the code so that you get the expected result. +*/ + +function isNegative(number) { + if (number < 0) { + return true; + } else { + return false; + } +} + +function isBetween5and10(number2) { + if (number2 >= 5 && number2 <= 10) { + return true; + } else { + return false; + } +} + +function isShortName(name) { + let isNameShort = new RegExp(/^([a-z]?$)/i); + return isNameShort.test(name); +} + +function startsWithD(daniel) { + let nameStartD = daniel[0]; + let result = nameStartD == "D"; + return result; +} + +/* + DO NOT EDIT BELOW THIS LINE + --------------------------- */ + +console.log("Is -10 is a negative number?", isNegative(-10)); +console.log("Is 5 a negative number?", isNegative(5)); +console.log("Is 10 in the range 5-10?", isBetween5and10(10)); +console.log("Is Daniel a short name?", isShortName("Daniel")); +console.log("Does Daniel start with 'D'?", startsWithD("Daniel")); + +/* + EXPECTED RESULT + --------------- + Is -10 is a negative number? true + Is 5 a negative number? false + Is 10 in the range 5-10? true + Is Daniel a short name? true + Does Daniel start with 'D'? +*/ diff --git a/exercises/E-conditionals/README.md b/exercises/E-conditionals/README.md new file mode 100644 index 000000000..420ed1da9 --- /dev/null +++ b/exercises/E-conditionals/README.md @@ -0,0 +1,61 @@ +Like humans, computer programs make decisions based on information given to them. **Conditionals** are a way of representing these decisions in code. + +For example: + +- In a game, if the player has 0 lives, then the game is over +- In a weather app, if rain is forecast, a picture of rain clouds is shown + +The most common type of conditional is the **if statement**. + +An if statment runs some code if a condition is met. If the condition is not met, then the code will skipped. + +```js +let isHappy = true; + +if (isHappy) { + console.log("I am happy"); +} +``` + +The code in paratheses - e.g. `(isHappy)` - is the condition. The condition can be _any_ expression. The following are all valid conditions: + +```js +// boolean value +if (true) { + // do something +} + +// variable assigned to boolean value +if (isHappy) { + // do something +} + +// equality operator returns a boolean value +if (1 + 1 === 2) { + // do something +} + +// comparison operator returns a boolean value +if (10 > 5) { + // do something +} + +// function call returns boolean value +if (greaterThan10(5)) { + // do something +} +``` + +An if statement runs code when a condition is met. What if the condition is not met? Sometimes you want to run an alternative bit of code. + +An **if...else statement** also runs code when the condition is _not_ met. + +```js +let isHappy = true; + +if (isHappy) { + console.log("I am happy 😄"); +} else { + console.log("I am not happy 😢"); +} +``` diff --git a/exercises/E-conditionals/exercise.js b/exercises/E-conditionals/exercise.js new file mode 100644 index 000000000..596430e01 --- /dev/null +++ b/exercises/E-conditionals/exercise.js @@ -0,0 +1,32 @@ +/* + Conditionals + --------------------------------- + Add an if statement to check Daniel's role in a CYF class. + 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." +*/ + +let name = "Daniel"; +let danielsRole = "mentor"; + +function checkRole() { + if ((danielsRole = Mentor)) { + let result = "Hi, I'm Daniel, I'm a mentor"; + return result; + // Additional + } else if ((danielsRole = "none")) { + let result = "Hi, I'm Daniel, I'm not involved in CYF"; + return result; + } else { + let result = "Hi, I'm Daniel, I'm a student"; + return result; + } +} + + + +/* +EXPECTED RESULT +--------------- +Hi, I'm Daniel, I'm a mentor. +*/ diff --git a/exercises/F-predicates/README.md b/exercises/F-predicates/README.md new file mode 100644 index 000000000..00862de1a --- /dev/null +++ b/exercises/F-predicates/README.md @@ -0,0 +1,16 @@ +**Predicate** is a fancy word for a function that returns a boolean value. + +These functions are very useful because they let you test if a value satisifies certain requirements. + +```js +function isNumber(value) { + return typeof value === "number"; +} + +isNumber(10); // returns true +isNumber("hello"); // returns false +``` + +JavaScript programmers often give predicate functions a name that starts with a verb e.g. `isBig`, `isNegative`, `isActive`, `shouldUpdate`, + +Calling a predicate function is like asking a question: "is this value a number". The return value is the answer to your question. diff --git a/exercises/F-predicates/exercise.js b/exercises/F-predicates/exercise.js new file mode 100644 index 000000000..64134daa7 --- /dev/null +++ b/exercises/F-predicates/exercise.js @@ -0,0 +1,39 @@ +/* + Predicates + --------------------------------- + Write two predicate functions + The variables should have values that match the expected results. +*/ + +// Finish the predicate function to test if the passed number is negative (less than zero) +function isNegative(number) { + let checkNagative = number < 0; + return checkNagative; +} + +// Finish the predicate function to test if the passed number is between 0 and 10 +function isBetweenZeroAnd10(number) { + if (number >= 0 && number <= 10) { + return true; + } else { + return false; + } +} + +/* + DO NOT EDIT BELOW THIS LINE + --------------------------- */ + +console.log(`Is 5 negative? ${isNegative(5)}`); +console.log(`Is -5 negative? ${isNegative(-5)}`); +console.log(`Is 5 between 0 and 10? ${isBetweenZeroAnd10(5)}`); +console.log(`Is -5 between 0 and 10? ${isBetweenZeroAnd10(-5)}`); + +/* + EXPECTED RESULT + --------------- + 1. Is 5 negative? false + 2. Is -5 negative? true + 3. Is 5 between 0 and 10? true + 5. Is -5 between 0 and 10? false +*/ \ No newline at end of file diff --git a/exercises/G-conditionals-2/README.md b/exercises/G-conditionals-2/README.md new file mode 100644 index 000000000..a830cf368 --- /dev/null +++ b/exercises/G-conditionals-2/README.md @@ -0,0 +1,24 @@ +A common use of if statements is inside of functions. + +```js +function getGrade(score) { + if (score >= 80) { + return "A"; + } + if (score >= 60) { + return "B"; + } +} +``` + +You can also write this using `else if`: + +```js +function getGrade(score) { + if (score >= 80) { + return "A"; + } else if (score >= 60) { + return "B"; + } +} +``` diff --git a/exercises/G-conditionals-2/exercise-1.js b/exercises/G-conditionals-2/exercise-1.js new file mode 100644 index 000000000..22b9e166f --- /dev/null +++ b/exercises/G-conditionals-2/exercise-1.js @@ -0,0 +1,34 @@ +/* + Conditionals + --------------------------------- + Write a function to test if a provided number is negative or positive + - if number is less than zero, return the word "negative" + - if number is more or equal to zero, return the word "positive" +*/ + +function negativeOrPositive(number) { + if (number >= 0) { + return "Positive"; + } else { + return "Negative"; + } +} + +/* + DO NOT EDIT BELOW THIS LINE + --------------------------- */ +let number1 = 5; +let number2 = -1; +let number3 = 0; + +console.log(number1 + " is " + negativeOrPositive(number1)); +console.log(number2 + " is " + negativeOrPositive(number2)); +console.log(number3 + " is " + negativeOrPositive(number3)); + +/* + EXPECTED RESULT + --------------- + 5 is positive + -1 is negative + 0 is positive +*/ diff --git a/exercises/G-conditionals-2/exercise-2.js b/exercises/G-conditionals-2/exercise-2.js new file mode 100644 index 000000000..f990f7fb8 --- /dev/null +++ b/exercises/G-conditionals-2/exercise-2.js @@ -0,0 +1,35 @@ +/* + Conditionals + --------------------------------- + Write a function that checks if a student has passed + - if the grade is less than 50 then return "failed" + - if 50 or higher then return "passed" + +*/ + +function studentPassed(grade) { + if (grade >= 50) { + return "Passed"; + } else { + return "Failed"; + } +} + +/* +DO NOT EDIT BELOW THIS LINE +--------------------------- */ +let grade1 = 49; +let grade2 = 50; +let grade3 = 100; + +console.log("'" + grade1 + "': " + studentPassed(grade1)); +console.log("'" + grade2 + "': " + studentPassed(grade2)); +console.log("'" + grade3 + "': " + studentPassed(grade3)); + +/* +EXPECTED RESULT +--------------- +'49': failed +'50': passed +'100': passed +*/ diff --git a/exercises/G-conditionals-2/exercise-3.js b/exercises/G-conditionals-2/exercise-3.js new file mode 100644 index 000000000..99d4d760a --- /dev/null +++ b/exercises/G-conditionals-2/exercise-3.js @@ -0,0 +1,43 @@ +/* + Conditionals + --------------------------------- + Write a function that checks if a student has passed + - if the mark is 80 or higher then the grade is "A" + - if the mark is lower than 80 and greater than 60 then the grade is "B" + - if the mark is 60 or lower but no lower than 50 then the grade is "C" + - Otherwise the grade is "F" +*/ + +function calculateGrade(mark) { + if (mark >= 80) { + return "A"; + } else if (mark > 60 && mark < 80) { + return "B"; + } else if (mark <= 60 && mark >= 50) { + return "C"; + } else { + return "F"; + } +} + +/* +DO NOT EDIT BELOW THIS LINE +--------------------------- */ +let grade1 = 49; +let grade2 = 90; +let grade3 = 70; +let grade4 = 55; + +console.log("'" + grade1 + "': " + calculateGrade(grade1)); +console.log("'" + grade2 + "': " + calculateGrade(grade2)); +console.log("'" + grade3 + "': " + calculateGrade(grade3)); +console.log("'" + grade4 + "': " + calculateGrade(grade4)); + +/* + EXPECTED RESULT + --------------- + '49': F + '90': A + '70': B + '55': C + */ diff --git a/exercises/G-conditionals-2/exercise-4.js b/exercises/G-conditionals-2/exercise-4.js new file mode 100644 index 000000000..3b93791f2 --- /dev/null +++ b/exercises/G-conditionals-2/exercise-4.js @@ -0,0 +1,38 @@ +/* + Conditionals + --------------------------------- + Write a function that checks if a sentence contains the word "code" + - if the sentence contains the word "code" then return true + - otherwise return false + + Hint: Google how to check if a string contains a word +*/ + +function containsCode(sentence) { + let string = sentence; + let word = string.includes("code"); + if ((string = word)) { + return true; + } else { + return false; + } +} + +/* +DO NOT EDIT BELOW THIS LINE +--------------------------- */ +let sentence1 = "code your future"; +let sentence2 = "draw your future"; +let sentence3 = "design your future"; + +console.log("'" + sentence1 + "': " + containsCode(sentence1)); +console.log("'" + sentence2 + "': " + containsCode(sentence2)); +console.log("'" + sentence3 + "': " + containsCode(sentence3)); + +/* + EXPECTED RESULT + --------------- + 'code your future': true + 'draw your future': false + 'design your future': false + */ diff --git a/exercises/H-array-literals/README.md b/exercises/H-array-literals/README.md new file mode 100644 index 000000000..f33c657fc --- /dev/null +++ b/exercises/H-array-literals/README.md @@ -0,0 +1,23 @@ +If you ever find yourself writing code like this... + +```js +let mentor1 = "Daniel"; +let mentor2 = "Irina"; +let mentor3 = "Rares"; +``` + +...then it's probably time to use an **array**! + +Arrays are data structures that hold a list of values. + +```js +let mentors = ["Daniel", "Irina", "Rares"]; +``` + +Arrays can hold any type of value (although almost always you only have one data type per array). + +```js +let testScores = [16, 49, 85]; +let grades = ["F", "D", "A"]; +let greetings = ["Hello, how are you?", "Hi! Nice to meet you!"]; +``` diff --git a/exercises/H-array-literals/exercise.js b/exercises/H-array-literals/exercise.js new file mode 100644 index 000000000..0062c63b3 --- /dev/null +++ b/exercises/H-array-literals/exercise.js @@ -0,0 +1,21 @@ +/* + Array literals + -------------- + Declare some variables assigned to arrays of values +*/ + +let numbers = [1,2,3,4,5,6,7,8,9,10]; // add numbers from 1 to 10 into this array +let mentors = ["Daniel", "Irina", "Rares"]; // Create an array with the names of the mentors: Daniel, Irina and Rares + +/* + DO NOT EDIT BELOW THIS LINE + --------------------------- */ +console.log(numbers); +console.log(mentors); + +/* + EXPECTED RESULT + --------------- + [1,2,3,4,5,6,7,8,9,10] + ['Daniel', 'Irina', 'Rares'] +*/ diff --git a/exercises/I-array-properties/README.md b/exercises/I-array-properties/README.md new file mode 100644 index 000000000..8daffa237 --- /dev/null +++ b/exercises/I-array-properties/README.md @@ -0,0 +1,13 @@ +Arrays, like strings, have a `length` property. + +You can check this by starting a node console in your terminal. + +```sh +$ node +> let arr = [1, 2, 3]; +undefined +> arr +[1, 2, 3] +> arr.length +3 +``` diff --git a/exercises/I-array-properties/exercise.js b/exercises/I-array-properties/exercise.js new file mode 100644 index 000000000..f24a6d21a --- /dev/null +++ b/exercises/I-array-properties/exercise.js @@ -0,0 +1,32 @@ +/* + Array properites + ---------------- + Complete the function to test if an array is empty (has no values in it) + +*/ + +function isEmpty(arr) { + let check = arr.length; + if (check === 0) { + return true; + } else { + return false; // complete this statement + } + +} + +/* + DO NOT EDIT BELOW THIS LINE + --------------------------- */ +let numbers = [1, 2, 3]; +let names = []; + +console.log(isEmpty(numbers)); +console.log(isEmpty(names)); + +/* + EXPECTED RESULT + --------------- + false + true +*/ diff --git a/exercises/J-array-get-set/README.md b/exercises/J-array-get-set/README.md new file mode 100644 index 000000000..52a6fdfee --- /dev/null +++ b/exercises/J-array-get-set/README.md @@ -0,0 +1,26 @@ +You can **get** a single value out of an array using **bracket notation**. + +```sh +$ node +> let ingredients = ["Flour", "Water", "Salt"]; +undefined +> ingredients[0] +Flour +> ingredients[1] +Water +> ingredients.length +3 +``` + +Did you notice how we use `[0]` to get the first value? In programming we count starting at zero. + +> The number inside of the brackets is called an **index**. Index just means the position of the item within the array. + +You can also **set** a value using bracket notation and an assignment operator (`=`). + +```js +let scores = [80, 41, 47]; + +scores[2] = 29; // Change the last score +scores[3] = 51; // Add a new score +``` diff --git a/exercises/J-array-get-set/exercise.js b/exercises/J-array-get-set/exercise.js new file mode 100644 index 000000000..d8286363c --- /dev/null +++ b/exercises/J-array-get-set/exercise.js @@ -0,0 +1,31 @@ +/* + Array getters + ------------------------- + Complete the functions below to get the first and last values from the array +*/ + +function first(arr) { + return arr.slice(0, 1)[0]; // complete this statement +} + +function last(arr) { + return arr[arr.length - 1]; // complete this statement +} + +/* + DO NOT EDIT BELOW THIS LINE + --------------------------- */ +let numbers = [1, 2, 3]; +let names = ["Irina", "Ashleigh", "Mozafar", "Joe"]; + +console.log(first(numbers)); +console.log(last(numbers)); +console.log(last(names)); + +/* + EXPECTED RESULT + --------------- + 1 + 3 + Joe +*/ diff --git a/exercises/J-array-get-set/exercises2.js b/exercises/J-array-get-set/exercises2.js new file mode 100644 index 000000000..ed97f55be --- /dev/null +++ b/exercises/J-array-get-set/exercises2.js @@ -0,0 +1,20 @@ +/* + Array setters + ------------- + WITHOUT changing the array literal declaration, + - assign the number 4 to the end of this array + - change the first value in the array to the number 1 +*/ + +let numbers = [1, 2, 3]; // Don't change this array literal declaration +numbers[3] = 4; +/* + DO NOT EDIT BELOW THIS LINE + --------------------------- */ +console.log(numbers); + +/* + EXPECTED RESULT + --------------- + [1, 2, 3, 4] +*/ diff --git a/extra/1-radio-stations.js b/extra/1-radio-stations.js new file mode 100644 index 000000000..577076e99 --- /dev/null +++ b/extra/1-radio-stations.js @@ -0,0 +1,67 @@ +/** + * Finding a radio station, and a good one, can be hard manually. + * Let's use some code to help us build a program that helps us scan + * the radio waves for some good music. + */ + +/** + * First, let's create a function that creates a list of all the frequencies. + * Call this function `getAllFrequencies`. + * + * This function should: + * - Create an array starting at 87 and ending in 108 + * - Should return this array to use in other functions + */ + +// `getAllFrequencies` goes here + +/** + * 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 isRadioStation that takes an integer as an argument and returns a boolean. + * - Return only the frequencies that are radio stations. + */ +// `getStations` goes here + +/* + * ======= TESTS - DO NOT MODIFY ======= + * Note: You are not expected to understand everything below this comment! + */ + +function getAvailableStations() { + // Using `stations` as a property as defining it as a global variable wouldn't + // always make it initialized before the function is called + if (!getAvailableStations.stations) { + const stationCount = 4; + getAvailableStations.stations = []; + while (getAvailableStations.stations.length < stationCount) { + let randomFrequency = Math.floor(Math.random() * (108 - 87 + 1) + 87); + if (!getAvailableStations.stations.includes(randomFrequency)) { + getAvailableStations.stations.push(randomFrequency); + } + } + getAvailableStations.stations.sort(function (frequencyA, frequencyB) { + return frequencyA - frequencyB; + }); + } + + return getAvailableStations.stations; +} + +function isRadioStation(frequency) { + return getAvailableStations().includes(frequency); +} + +test("getAllFrequencies() returns all frequencies between 87 and 108", () => { + expect(getAllFrequencies()).toEqual([ + 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, + 105, 106, 107, 108, + ]); +}); + +test("getStations() returns all the available stations", () => { + expect(getStations()).toEqual(getAvailableStations()); +}); diff --git a/mandatory/1-fix-functions.js b/mandatory/1-fix-functions.js new file mode 100644 index 000000000..9a8268f7a --- /dev/null +++ b/mandatory/1-fix-functions.js @@ -0,0 +1,85 @@ +/* Fix Functions + + Aim: to understand the change code inside functions + + See the below functions. They are syntactically correct but are not outputting the right results. + + Run the tests and see how you can fix them. + + NOTE:Only make edits inside the function + +*/ + +function mood() { + let isHappy = true; + + if (isHappy) { + return "I am happy"; + } else { + return "I am not happy"; + } +} + +function greaterThan10(num) { + let isBigEnough; + + if (isBigEnough) { + return "num is greater than 10"; + } else { + return "num is not big enough"; + } +} + +function get3rdIndex(arr) { + let index = 3; + let element; + + return element; +} + +/* ======= TESTS - DO NOT MODIFY ===== */ + +test("mood function works for true", () => { + expect(mood(true)).toEqual("I am happy"); +}); + +test("mood function works for false", () => { + expect(mood(false)).toEqual("I am not happy"); +}); + +test("greaterThanTen function works for value greater than 10", () => { + expect(greaterThan10(11)).toEqual("num is greater than 10"); +}); + +test("greaterThanTen function works for value much greater than 10", () => { + expect(greaterThan10(96)).toEqual("num is greater than 10"); +}); + +test("greaterThanTen function works for value less than 10", () => { + expect(greaterThan10(9)).toEqual("num is not big enough"); +}); + +test("greaterThanTen function works for value equal to 10", () => { + expect(greaterThan10(10)).toEqual("num is not big enough"); +}); + +test("get3rdIndex function works with strings", () => { + const strings = ["fruit", "banana", "apple", "strawberry", "raspberry"]; + const copyOfOriginal = strings.slice(); + expect(get3rdIndex(strings)).toEqual("strawberry"); + // Make sure get3rdIndex didn't change its input array. + expect(strings).toEqual(copyOfOriginal); +}); + +test("get3rdIndex function works with numbers", () => { + const numbers = [11, 37, 62, 18, 19, 3, 30]; + const copyOfOriginal = numbers.slice(); + expect(get3rdIndex(numbers)).toEqual(18); + // Make sure get3rdIndex didn't change its input array. + expect(numbers).toEqual(copyOfOriginal); +}); + +test("get3rdIndex returns undefined if not enough elements", () => { + const numbers = [5, 10]; + expect(get3rdIndex(numbers)).toBeUndefined(); +}); diff --git a/mandatory/2-function-creation.js b/mandatory/2-function-creation.js new file mode 100644 index 000000000..af8bbf13e --- /dev/null +++ b/mandatory/2-function-creation.js @@ -0,0 +1,91 @@ +/* +Complete the function to check if the variable `num` satisfies the following requirements: +- is a number +- is even +- is less than or equal to 100 +Tip: use logical operators +*/ + +function validate(num) {} + +/* +Write a function that: +- takes a number as input +- return a string formatted as percentages (e.g. 10 => "10%") +- the number must be rounded to 2 decimal places +- numbers greater 100 must be replaced with 100 +*/ + +function formatPercentage(num) {} + +/* +Write a function that: +- takes an array of strings as input +- removes any spaces in the beginning or end of each string +- removes any forward slashes (/) in each string +- makes all strings all lowercase +*/ +function tidyUpStrings(arrayOfStrings) {} + +/* ======= TESTS - DO NOT MODIFY ===== */ + +test("validate function accepts valid even number", () => { + expect(validate(10)).toEqual(true); +}); + +test("validate function accepts other valid even number", () => { + expect(validate(18)).toEqual(true); +}); + +test("validate function accepts exactly 100", () => { + expect(validate(100)).toEqual(true); +}); + +test("validate function rejects odd number", () => { + expect(validate(17)).toEqual(false); +}); + +test("validate function rejects string", () => { + expect(validate("Ten")).toEqual(false); +}); + +test("validate function rejects stringified number", () => { + expect(validate("10")).toEqual(false); +}); + +test("validate function rejects too large number", () => { + expect(validate(108)).toEqual(false); +}); + +test.each([ + [23, "23%"], + [18.103, "18.1%"], + [187.2, "100%"], + [0.372, "0.37%"], +])("formatPercentage function works for %s", (input, expected) => { + expect(formatPercentage(input)).toEqual(expected); +}); + +test("tidyUpString function works", () => { + expect( + tidyUpStrings([ + "/Daniel", + " /Sanyia", + "AnTHonY", + "irina", + " Gordon", + "ashleigh ", + " Alastair ", + " anne marie ", + ]) + ).toEqual([ + "daniel", + "sanyia", + "anthony", + "irina", + "gordon", + "ashleigh", + "alastair", + "anne marie", + ]); +}); diff --git a/mandatory/3-playing-computer.js b/mandatory/3-playing-computer.js new file mode 100644 index 000000000..0f448f3b7 --- /dev/null +++ b/mandatory/3-playing-computer.js @@ -0,0 +1,42 @@ +/* + 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? + 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) { + return a + b; +}; + +const f2 = function (a, b) { + return a + b + x; +}; + +console.log(x); +console.log(a); +console.log(b); + +for (let i = 0; i < 5; ++i) { + a = a + 1; + if (i % 2 === 0) { + const d = f2(i, x); + console.log(d); + } else { + const e = f1(i, a); + console.log(e); + } +} diff --git a/package.json b/package.json index 93e0861e3..d939d9d86 100644 --- a/package.json +++ b/package.json @@ -1,34 +1,21 @@ { - "name": "javascript-core-1-coursework-week1", + "name": "javascript-core-1-coursework-week2", "version": "1.0.0", - "description": "Exercises for JS1 Week 1", + "description": "Exercises for JS1 Week 2", "license": "CC-BY-SA-4.0", "scripts": { - "test": "jest" + "test": "jest --testRegex='mandatory[/\\\\].*\\.js$' --testPathIgnorePatterns=playing-computer", + "extra-tests": "jest --testRegex='extra[/\\\\].*\\.js$'" }, "repository": { "type": "git", - "url": "git+https://github.com/CodeYourFuture/JavaScript-Core-1-Coursework-Week1.git" + "url": "git+https://github.com/CodeYourFuture/JavaScript-Core-1-Coursework-Week2.git" }, "bugs": { - "url": "https://github.com/CodeYourFuture/JavaScript-Core-1-Coursework-Week1/issues" + "url": "https://github.com/CodeYourFuture/JavaScript-Core-1-Coursework-Week2/issues" }, - "jest": { - "setupFilesAfterEnv": ["jest-extended"], - "projects": [ - { - "displayName": "mandatory", - "testMatch": ["/mandatory/*.js"] - }, - { - "displayName": "extra", - "testMatch": ["/extra/*.js"] - } - ] - }, - "homepage": "https://github.com/CodeYourFuture/JavaScript-Core-1-Coursework-Week1#readme", + "homepage": "https://github.com/CodeYourFuture/JavaScript-Core-1-Coursework-Week2#readme", "devDependencies": { - "jest": "^26.6.3", - "jest-extended": "^0.11.5" + "jest": "^26.6.3" } }