Skip to content

Glasgow | ITP-May | Salah Ahmed | Module-Structuring-and-Testing-Data | Sprint-2 #512

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Sprint-1/1-key-exercises/1-count.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,8 @@ let count = 0;
count = count + 1;

// Line 1 is a variable declaration, creating the count variable with an initial value of 0
// Describe what line 3 is doing, in particular focus on what = is doing
// Describe what line 3 is doing, in particular focus on what = is doing

// Line 3 is updating the value of the count variable by adding 1 to its current value. The = operator is used for assignment, meaning it takes the value on the right (count + 1) and assigns it to the variable on the left (count).
// The expression count + 1 calculates the new value, and then the = operator assigns this new value back to the count variable.
// The count variable now holds the value 1, which is the result of the initial value (0) plus 1.
6 changes: 6 additions & 0 deletions Sprint-1/1-key-exercises/2-initials.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ let lastName = "Johnson";
// This should produce the string "CKJ", but you must not write the characters C, K, or J in the code of your solution.

let initials = ``;
initials = firstName[0] + middleName[0] + lastName[0];
// The above code uses the bracket notation to access the first character of each string.
console.log(initials); // Output: CKJ
// The code above uses the bracket notation to access the first character of each string.
// The firstName[0] accesses the first character of the firstName string, which is "C".


// https://www.google.com/search?q=get+first+character+of+string+mdn

8 changes: 6 additions & 2 deletions Sprint-1/1-key-exercises/3-paths.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ console.log(`The base part of ${filePath} is ${base}`);
// Create a variable to store the dir part of the filePath variable
// Create a variable to store the ext part of the variable

const dir = ;
const ext = ;
const dir = filePath.slice(0, lastSlashIndex);
const lastDotIndex = base.lastIndexOf(".");
const ext = base.slice(lastDotIndex + 1);

console.log(`The dir part is ${dir}`);
console.log(`The ext part is ${ext}`);

// https://www.google.com/search?q=slice+mdn
14 changes: 14 additions & 0 deletions Sprint-1/1-key-exercises/4-random.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,17 @@ const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
// Try breaking down the expression and using documentation to explain what it means
// It will help to think about the order in which expressions are evaluated
// Try logging the value of num and running the program several times to build an idea of what the program is doing

console.log(`The random number is ${num}`);
// The variable num represents a random integer between the values of minimum (1) and maximum (100), inclusive.
// The expression Math.random() generates a random floating-point number between 0 (inclusive) and 1 (exclusive).
// The expression (maximum - minimum + 1) calculates the range of possible values (100 - 1 + 1 = 100).
// Multiplying Math.random() by this range scales the random number to the desired range.
// Adding minimum shifts the range to start at the minimum value (1).
// Finally, Math.floor() rounds down the result to the nearest whole number, ensuring that num is an integer.
// Therefore, num will always be a whole number between 1 and 100, inclusive.
// This means that every time the program is run, it will produce a different random number within this range.
// The program logs the value of num to the console, showing the generated random number each time it is executed.
// This is useful for scenarios where you need a random number, such as in games, simulations, or testing.
// The use of Math.random(), Math.floor(), and the arithmetic operations ensures that the random number is uniformly distributed across the specified range.
// The program can be run multiple times to see different random numbers generated each time, demonstrating the randomness of the output.
18 changes: 18 additions & 0 deletions Sprint-1/1-key-exercises/test.js

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's good to see you doing tests to figure things out. Should this testing be included in your pull request?

Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
function checkTime(time){

return time.slice(0,1)+time.slice(1,2)
}

console.log(checkTime("12:34")); // Output: 12
console.log(checkTime("23:59")); // Output: 23

num1 = checkTime("13:34");

if (num1 > 12 && num1 < 24) {

console.log("PM");

} else
{
console.log("AM");
}
4 changes: 2 additions & 2 deletions Sprint-1/2-mandatory-errors/0.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
This is just an instruction for the first activity - but it is just for human consumption
We don't want the computer to run these 2 lines - how can we solve this problem?
//This is just an instruction for the first activity - but it is just for human consumption
//We don't want the computer to run these 2 lines - how can we solve this problem?
12 changes: 10 additions & 2 deletions Sprint-1/2-mandatory-errors/1.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
// trying to create an age variable and then reassign the value by 1

const age = 33;
age = age + 1;
let age = 33;
age = age + 1;
// The above code will throw an error because 'age' is a constant variable declared with 'const'.
// In JavaScript, variables declared with 'const' cannot be reassigned a new value after their initial assignment.
// To fix this, you can declare 'age' using 'let' instead of 'const', allowing it to be reassigned.
// let age = 33;
console.log(age); // Output: 34
// The code above declares a variable 'age' with an initial value of 33.
// Then, it reassigns the value of 'age' by adding 1 to its current value.
// The final value of 'age' will be 34, which is the result of the initial value (33) plus 1.
9 changes: 8 additions & 1 deletion Sprint-1/2-mandatory-errors/2.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
// Currently trying to print the string "I was born in Bolton" but it isn't working...
// what's the error ?

console.log(`I was born in ${cityOfBirth}`);
//console.log(`I was born in ${cityOfBirth}`);
//const cityOfBirth = "Bolton";

// The error occurs because the variable 'cityOfBirth' is being used before it has been declared.
// To fix this, you should declare the variable 'cityOfBirth' before using it in the console.log statement.
// Here's the corrected code:
const cityOfBirth = "Bolton";
console.log(`I was born in ${cityOfBirth}`);
// Now, the code will correctly print "I was born in Bolton" without any errors.
14 changes: 13 additions & 1 deletion Sprint-1/2-mandatory-errors/3.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
const cardNumber = 4533787178994213;
const last4Digits = cardNumber.slice(-4);
//const last4Digits = cardNumber.slice(-4);

// The last4Digits variable should store the last 4 digits of cardNumber
// However, the code isn't working
// Before running the code, make and explain a prediction about why the code won't work
// Then run the code and see what error it gives.
// Consider: Why does it give this error? Is this what I predicted? If not, what's different?
// Then try updating the expression last4Digits is assigned to, in order to get the correct value

// Prediction: The code will not work because the `slice` method is being called on a number (cardNumber), which does not have a `slice` method. The `slice` method is typically used with strings or arrays, not numbers.
// Running the code will likely result in a TypeError indicating that `slice` is not a function or is not defined for the number type.
// Running the code confirms the prediction, as it throws an error: "TypeError: cardNumber.slice is not a function".
// To fix this, we need to convert the cardNumber to a string before using the `slice` method.
const last4Digits = String(cardNumber).slice(-4);
// Now, last4Digits will correctly store the last 4 digits of cardNumber.
console.log(`The last 4 digits of the card number are: ${last4Digits}`);
// This will output: "The last 4 digits of the card number are: 4213"

// The code now works correctly, and the last4Digits variable contains the last four digits of the card number as a string.
// The final output will be "The last 4 digits of the card number are: 4213".
4 changes: 2 additions & 2 deletions Sprint-1/2-mandatory-errors/4.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
const 12HourClockTime = "20:53";
const 24hourClockTime = "08:53";
const twelveHourClockTime = "20:53";
const twentyFourHourClockTime = "08:53";
25 changes: 24 additions & 1 deletion Sprint-1/3-mandatory-interpret/1-percentage-change.js

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a) You've correctly identified 2 function calls. How did you decide these were functions? Can you see any others?
b) Good fix. Can you see a way to make the coding style of the fixed code consistent with the rest of the program?
c) and d) Good!
e) Good explanation. Can you think of a reason why you would want to remove the comma from the number before converting it?

Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ let carPrice = "10,000";
let priceAfterOneYear = "8,543";

carPrice = Number(carPrice.replaceAll(",", ""));
priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," ""));
priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",",""));

const priceDifference = carPrice - priceAfterOneYear;
const percentageChange = (priceDifference / carPrice) * 100;
Expand All @@ -20,3 +20,26 @@ console.log(`The percentage change is ${percentageChange}`);
// d) Identify all the lines that are variable declarations

// e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression?


// a) There are 2 function calls in this file:
// 1. `carPrice.replaceAll(",", "")` on line 4
// 2. `priceAfterOneYear.replaceAll(",", "")` on line 5


// b) The error occurs on line 5 because there is a syntax error in the `replaceAll` method call.
// The correct syntax should be `replaceAll(",", "")` instead of `replaceAll("," "")`.
// To fix this, you need to add a comma between the two arguments.

// c) The variable reassignment statements are:
// 1. `carPrice = Number(carPrice.replaceAll(",", ""));` on line 4
// 2. `priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", ""));` on line 5

// d) The variable declarations are:
// 1. `let carPrice = "10,000";` on line 1
// 2. `let priceAfterOneYear = "8,543";` on line 2
// 3. `const priceDifference = carPrice - priceAfterOneYear;` on line 7
// 4. `const percentageChange = (priceDifference / carPrice) * 100;` on line 8

// e) The expression `Number(carPrice.replaceAll(",", ""))` is converting the string representation of the car price (which includes commas) into a number.
// The `replaceAll(",", "")` part removes all commas from the string, and then the `Number()` function converts the resulting string into a numeric value.
26 changes: 25 additions & 1 deletion Sprint-1/3-mandatory-interpret/2-time-format.js

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

b) What is line 10 doing? How would you describe that kind of code?
f) The calculations may work, but can you think of any cases where the formatted result might not look quite right?

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const movieLength = 8784; // length of movie in seconds
const movieLength = 8314.5; // length of movie in seconds

const remainingSeconds = movieLength % 60;
const totalMinutes = (movieLength - remainingSeconds) / 60;
Expand All @@ -23,3 +23,27 @@ console.log(result);
// e) What do you think the variable result represents? Can you think of a better name for this variable?

// f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer

// a) There are 6 variable declarations in this program:
// 1. `const movieLength = 8784;`
// 2. `const remainingSeconds = movieLength % 60;`
// 3. `const totalMinutes = (movieLength - remainingSeconds) / 60;`
// 4. `const remainingMinutes = totalMinutes % 60;`
// 5. `const totalHours = (totalMinutes - remainingMinutes) / 60;`
// 6. `const result = `${totalHours}:${remainingMinutes}:${remainingSeconds}`;`

// b) There are 0 function calls in this program.
// All operations are arithmetic operations and do not involve calling any functions.

// c) The expression `movieLength % 60` calculates the remainder when `movieLength` (the total length of the movie in seconds) is divided by 60.
// This gives the number of seconds that do not complete a full minute, effectively providing the remaining seconds after converting the total movie length into minutes.

// d) The expression assigned to `totalMinutes` calculates the total number of minutes in the movie by subtracting the remaining seconds from the total movie length and then dividing by 60.
// It converts the total movie length from seconds to minutes, effectively giving the total number of complete minutes in the movie.

// e) The variable `result` represents the total duration of the movie formatted as "hours:minutes:seconds".
// A better name for this variable could be `formattedMovieDuration` or `movieDurationFormatted` to make it clear that it contains the movie's duration in a specific format.

// f) This code will work for all values of `movieLength` that are non-negative integers.
// However, if `movieLength` is negative, the calculations will still work but may not make sense in the context of a movie duration.

12 changes: 12 additions & 0 deletions Sprint-1/3-mandatory-interpret/3-to-pounds.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,15 @@ console.log(`£${pounds}.${pence}`);

// To begin, we can start with
// 1. const penceString = "399p": initialises a string variable with the value "399p"
// 2. const penceStringWithoutTrailingP = penceString.substring(0, penceString.length - 1):
// removes the trailing 'p' from the string, resulting in "399"
// 3. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"):
// pads the string with leading zeros to ensure it has at least 3 characters, resulting in "399"
// 4. const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2):
// extracts the pounds part of the string by taking all characters except the last two, resulting in "3"
// 5. const pence = paddedPenceNumberString
// .substring(paddedPenceNumberString.length - 2).padEnd(2, "0"):
// extracts the last two characters (the pence part) and pads it with trailing zeros to ensure it has 2 characters, resulting in "99"
// 6. console.log(`£${pounds}.${pence}`):
// prints the final formatted string representing the price in pounds, which is "£3.99"

15 changes: 15 additions & 0 deletions Sprint-1/4-stretch-explore/chrome.md

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You correctly identify the effect of prompt - can you think of a reason why you would want to use this?

Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,22 @@ invoke the function `alert` with an input string of `"Hello world!"`;

What effect does calling the `alert` function have?

A popup dialog appears in the browser window with the message "Hello world!" and an OK button.
It's a simple way to show a message to the user.

Now try invoking the function `prompt` with a string input of `"What is your name?"` - store the return value of your call to `prompt` in an variable called `myName`.

What effect does calling the `prompt` function have?
A popup appears that:

Shows the message: "What is your name?" Includes a text input field

Has OK and Cancel buttons


What is the return value of `prompt`?
The prompt() function returns:

The string the user types (e.g., "ٍSalah")

null if the user clicks Cancel instead of OK
16 changes: 16 additions & 0 deletions Sprint-1/4-stretch-explore/objects.md

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You found that the type of console is an 'object' - but can you think of a better way to describe what console stores? What is the purpose of the object?

Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,28 @@ In this activity, we'll explore some additional concepts that you'll encounter i
Open the Chrome devtools Console, type in `console.log` and then hit enter

What output do you get?
ƒ log() { [native code] }

Now enter just `console` in the Console, what output do you get back?
console {debug: ƒ, error: ƒ, info: ƒ, log: ƒ, warn: ƒ, …}


Try also entering `typeof console`

Answer the following questions:

What does `console` store?
'object'

What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean?
This syntax accesses a property or method on the console object.

The dot (.) is called dot notation.

console.log means:

Look inside the console object

Find the function named log

So console.log("Hi") is calling the log method of the console object.
10 changes: 9 additions & 1 deletion Sprint-2/1-key-errors/0.js

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you think of a way to make the fixed function more concise?

Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,13 @@ function capitalise(str) {
return str;
}

// =============> write your explanation here
// =============> write your explanation here
// The error occurs because the variable `str` is being redeclared inside the function, which is not allowed in JavaScript.
// The variable `str` is already defined as a parameter of the function, and attempting to declare it again with `let` causes a syntax error.
//

// =============> write your new code here
function capitalise(str) {
str = `${str[0].toUpperCase()}${str.slice(1)}`;
return str;
}
7 changes: 7 additions & 0 deletions Sprint-2/1-key-errors/1.js

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you do the prediction question first? (Line 4)

Can you see a way to change the fixed function to be more concise?

Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ function convertToPercentage(decimalNumber) {
console.log(decimalNumber);

// =============> write your explanation here
// The error occurs because the variable `decimalNumber` is being redeclared with `const` inside the function,
// which is not allowed since `decimalNumber` is already defined as a parameter of the function.

// Finally, correct the code to fix the problem
// =============> write your new code here
function convertToPercentage(decimalNumber) {
const percentage = `${decimalNumber * 100}%`;

return percentage;
}
9 changes: 9 additions & 0 deletions Sprint-2/1-key-errors/2.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,20 @@ function square(3) {
}

// =============> write the error message here
// The error occurs because the function parameter is incorrectly defined as a number (3) instead of a variable name.


// =============> explain this error message here
// The error message indicates that the function parameter is not defined correctly. In JavaScript, function parameters should be variable names, not literal values. The number `3` is being used as a parameter name, which is invalid syntax.


// Finally, correct the code to fix the problem

// =============> write your new code here

function square(num) {
return num * num;
}
// Now, you can call the function with a number to get the square
console.log(square(3)); // This will output 9, which is the square of 3.

5 changes: 5 additions & 0 deletions Sprint-2/2-mandatory-debug/0.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ function multiply(a, b) {
console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`);

// =============> write your explanation here
// The error occurs because the `multiply` function does not return a value; it only logs the result to the console.
// Therefore, when trying to use the result in the template literal, it results in `undefined` being printed.

// Finally, correct the code to fix the problem
// =============> write your new code here
function multiply(a, b) {
return a * b; // Return the result instead of logging it
}
9 changes: 9 additions & 0 deletions Sprint-2/2-mandatory-debug/1.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,14 @@ function sum(a, b) {
console.log(`The sum of 10 and 32 is ${sum(10, 32)}`);

// =============> write your explanation here
// The error occurs because the `return` statement is placed before the expression `a + b`,
// which means the function returns `undefined` instead of the sum of `a` and `b`.

// Finally, correct the code to fix the problem
// =============> write your new code here
function sum(a, b) {
return a + b; // Return the sum of a and b
}
console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); // This will now correctly output the sum
// The output will be: The sum of 10 and 32 is 42
// This indicates that the function now correctly computes and returns the sum of the two numbers.
24 changes: 24 additions & 0 deletions Sprint-2/2-mandatory-debug/2.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,34 @@ console.log(`The last digit of 806 is ${getLastDigit(806)}`);

// Now run the code and compare the output to your prediction
// =============> write the output here
// The last digit of 42 is 3
// The last digit of 105 is 3
// The last digit of 806 is 3

// Explain why the output is the way it is
// =============> write your explanation here
// The output is incorrect because the `getLastDigit` function is using a fixed variable `num`
// instead of taking the input number as an argument. Therefore, it always returns the last digit of `103`,
// which is `3`, regardless of the input provided in the console.log statements.

// Finally, correct the code to fix the problem
// =============> write your new code here
function getLastDigit(num) {
return num.toString().slice(-1);
}
// Now the function takes a number as an argument and returns its last digit
console.log(`The last digit of 42 is ${getLastDigit(42)}`);
console.log(`The last digit of 105 is ${getLastDigit(105)}`);
console.log(`The last digit of 806 is ${getLastDigit(806)}`);
// The last digit of 42 is 2
// The last digit of 105 is 5
// The last digit of 806 is 6


// This program should tell the user the last digit of each number.
// Explain why getLastDigit is not working properly - correct the problem
// The `getLastDigit` function was not working properly because it was using a fixed variable `num`
// instead of taking the input number as an argument. By modifying the function to accept a parameter,
// it now correctly returns the last digit of the provided number. The corrected function now works as intended,
// allowing it to return the last digit of any number passed to it as an argument.
// The final output now correctly displays the last digits of the numbers 42, 105, and 806 as 2, 5, and 6 respectively.
Loading