Skip to content

ITP | SAMI SARDARZAI | Module-Structuring-and-Testing-Data | WEEK 2 #202

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 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
7 changes: 5 additions & 2 deletions Sprint-1/errors/0.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
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?


// by adding comment we can slove this problem
7 changes: 5 additions & 2 deletions Sprint-1/errors/1.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
// trying to create an age variable and then reassign the value by 1

const age = 33;
age = age + 1;
// const age = 33;
// age = age + 1;

var age =23;
age =1;
9 changes: 8 additions & 1 deletion Sprint-1/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}`);
/*Answer : The problem is that cityOfBirth is used before it’s defined.
JavaScript runs code from top to bottom, so when console.log tries to use cityOfBirth, it hasn’t been set yet*/

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

console.log(`I was born in ${cityOfBirth}`);
10 changes: 9 additions & 1 deletion Sprint-1/errors/3.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
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

const last4Digits = cardNumber.toString().slice(-4);

console.log(last4Digits);

/* Prediction
The code won’t work because cardNumber is a number, and .slice() only works on strings and arrays.
To fix this, we need to turn cardNumber into a string first. */
6 changes: 4 additions & 2 deletions Sprint-1/errors/4.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
const 12HourClockTime = "20:53";
const 24hourClockTime = "08:53";
const HourClockTime = "20:53";
const hourClockTime = "08:53";

//we can not use number as a variable name !
4 changes: 4 additions & 0 deletions Sprint-1/exercises/count.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@ 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


//Line 3 increases count by 1. The = sets count to its new value.
console.log(count);
7 changes: 7 additions & 0 deletions Sprint-1/exercises/decimal.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,10 @@ const num = 56.5678;
// Create a variable called roundedNum and assign to it an expression that evaluates to 57 ( num rounded to the nearest whole number )

// Log your variables to the console to check your answers

const wholeNumberPart = Math.floor(num);
console.log(wholeNumberPart);
const decimalPart = num -wholeNumberPart;
console.log(decimalPart);
const roundedNum = Math.round(num);
console.log(roundedNum);
3 changes: 3 additions & 0 deletions Sprint-1/exercises/initials.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@ let lastName = "Johnson";

// Declare a variable called initials that stores the first character of each string.
// 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 = firstName.charAt(0)+middleName.charAt(0)+lastName.charAt(0);
console.log(initials);
6 changes: 6 additions & 0 deletions Sprint-1/exercises/paths.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@
const filePath = "/Users/mitch/cyf/Module-JS1/week-1/interpret/file.txt";
const lastSlashIndex = filePath.lastIndexOf("/");
const base = filePath.slice(lastSlashIndex + 1);
const dir = filePath.slice(0, lastSlashIndex);
const dotIndex = base.lastIndexOf(".");
const ext = base.slice(dotIndex);

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

// Create a variable to store the dir part of the filePath variable
// Create a variable to store the ext part of the variable
2 changes: 1 addition & 1 deletion Sprint-1/exercises/random.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const minimum = 1;
const maximum = 100;

const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;

console.log(num);
// In this exercise, you will need to work out what num represents?
// 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
Expand Down
30 changes: 28 additions & 2 deletions Sprint-1/interpret/percentage-change.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ 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;

console.log(`The percentage change is ${percentageChange}`);
console.log(`The percentage change is ${percentageChange} %`);

// Read the code and then answer the questions below

Expand All @@ -20,3 +20,29 @@ 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 4 function calls in total:
1. carPrice.replaceAll(",", "")
2. priceAfterOneYear.replaceAll(",", "")
3. Number(...) (used in two places)

b) The error occurs on the line where priceAfterOneYear is reassigned.
Reason: Missing comma in the replaceAll function call.
Fix: Correct it to priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", ""));

c) Variable reassignment statements:
1. carPrice = Number(carPrice.replaceAll(",", ""));
2. priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", ""));

d) Variable declaration statements:
1. let carPrice = "10,000";
2. let priceAfterOneYear = "8,543";
3. const priceDifference = carPrice - priceAfterOneYear;
4. const percentageChange = (priceDifference / carPrice) * 100;

e) The expression Number(carPrice.replaceAll(",", "")):
- Removes commas from the carPrice string and converts it to a number.
- Purpose: To get a numerical value from the string for calculations.
*/
8 changes: 8 additions & 0 deletions Sprint-1/interpret/time-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,11 @@ 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

// Answers:
// a) There are 5 variable declarations: movieLength, remainingSeconds, totalMinutes, remainingMinutes, totalHours
// b) There is 1 function call: console.log()
// c) movieLength % 60 finds leftover seconds that don’t fit into a full minute
// d) totalMinutes gives the number of complete minutes by removing extra seconds
// e) result is the formatted time (HH:MM:SS); a better name could be formattedTime
// f) Code works for any non-negative movieLength, but not for negative values
36 changes: 23 additions & 13 deletions Sprint-1/interpret/to-pounds.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,31 @@
const penceString = "399p";
const penceString = "399p"; // Initialize a string variable with the value "399p", which represents 399 pence.

const penceStringWithoutTrailingP = penceString.substring(
0,
penceString.length - 1
);
// Remove the trailing 'p' from the string
const penceStringWithoutTrailingP = penceString.substring(0, penceString.length - 1);
// This line uses the substring method to take all characters from the start up to (but not including) the last character 'p'.
// The result will be "399".

const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");
const pounds = paddedPenceNumberString.substring(
0,
paddedPenceNumberString.length - 2
);
// Pad the pence number string to ensure it has at least 3 digits
const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");
// This line ensures that the string has a minimum length of 3 characters, adding leading zeros if necessary.
// For example, "5" would become "005", but "399" stays as "399".

// Extract the pounds part from the padded pence string
const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2);
// This line takes all characters except the last two, which represent the pence.
// For "399", it results in "3", meaning 3 pounds.

// Extract the pence part from the padded pence string
const pence = paddedPenceNumberString
.substring(paddedPenceNumberString.length - 2)
.padEnd(2, "0");
.substring(paddedPenceNumberString.length - 2) // Get the last two characters, which represent the pence.
.padEnd(2, "0"); // Ensure that there are always two digits in the pence part, adding a zero if necessary.
// For "399", this gives "99". If it were "5", it would give "05".

// Print the final formatted price in pounds
console.log(`£${pounds}.${pence}`);
// This line combines pounds and pence into a string formatted as "£3.99".
// It uses template literals to insert the pound and pence values into the string.

console.log(`£${pounds}.${pence}`);

// This program takes a string representing a price in pence
// The program then builds up a string representing the price in pounds
Expand Down
12 changes: 12 additions & 0 deletions Sprint-2/debug/0.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
// Predict and explain first...

function multiply(a, b) {
// This function calculates the product of two numbers a and b.
// It logs the result (a * b) to the console but does not return anything.
console.log(a * b);
}


// Here, we are calling the multiply function with 10 and 32.
// The function will log the result (320) to the console.
console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`);


// However, the multiply function does not return a value.
// So, ${multiply(10, 32)} becomes undefined.
// The final output of this console.log will be:
// 1. First, 320 is printed from the multiply function.
// 2. Then, "The result of multiplying 10 and 32 is undefined" is printed.
11 changes: 9 additions & 2 deletions Sprint-2/debug/1.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
// Predict and explain first...

function sum(a, b) {
return;
a + b;
// The function has a 'return;' statement, which exits the function immediately.
// The line 'a + b' is ignored because it is placed after the 'return;' statement.
return; // The function ends here and returns undefined.
a + b; // This code is unreachable and will not execute.
}

// Here, we call the sum function with 10 and 32.
// Since the function returns undefined, the result in the template literal will be undefined.
console.log(`The sum of 10 and 32 is ${sum(10, 32)}`);

// Output:
// "The sum of 10 and 32 is undefined"
45 changes: 45 additions & 0 deletions Sprint-2/debug/2.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,59 @@
// Predict and explain first...

// Declare a constant `num` with the value 103
const num = 103;

// Define a function `getLastDigit()` which is intended to return the last digit of a number.
function getLastDigit() {
// Convert `num` to a string and use `slice(-1)` to get the last character of the string.
// But `num` is always 103, so this will always return '3' regardless of the argument passed.
return num.toString().slice(-1);
}

// Log the result of calling `getLastDigit(42)`
// The function doesn't use the argument 42 and will always return '3' (from `num` = 103).
console.log(`The last digit of 42 is ${getLastDigit(42)}`);

// Log the result of calling `getLastDigit(105)`
// The function doesn't use the argument 105 and will always return '3'.
console.log(`The last digit of 105 is ${getLastDigit(105)}`);

// Log the result of calling `getLastDigit(806)`
// The function doesn't use the argument 806 and will always return '3'.
console.log(`The last digit of 806 is ${getLastDigit(806)}`);


// This program should tell the user the last digit of each number.
// Explain why getLastDigit is not working properly - correct the problem


// Explanation:
// The original function was using a fixed constant `num` to get the last digit,
// which meant that it always returned the last digit of `103`, no matter
// what number was passed to the function.
// To fix this, we need to update the function to accept a number as an argument
// and use that argument to extract the last digit.

// Updated Function to Get Last Digit:
function getLastDigit(num) {
// Convert the number to a string and use `slice(-1)` to extract the last digit.
// We now use the `num` passed as an argument to the function.
return num.toString().slice(-1); // This will correctly return the last digit of the number passed.
}

// Logging the results for different numbers:

// Call the function with 42
// The function should return '2' as it's the last digit of 42
console.log(`The last digit of 42 is ${getLastDigit(42)}`); // Expected Output: 2

// Call the function with 105
// The function should return '5' as it's the last digit of 105
console.log(`The last digit of 105 is ${getLastDigit(105)}`); // Expected Output: 5

// Call the function with 806
// The function should return '6' as it's the last digit of 806
console.log(`The last digit of 806 is ${getLastDigit(806)}`); // Expected Output: 6


//NOTE : please comment first code if you want to run my codes ..
14 changes: 12 additions & 2 deletions Sprint-2/errors/0.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,17 @@
// call the function capitalise with a string input
// interpret the error message and figure out why an error is occurring

// Function to capitalize the first letter of the string
function capitalise(str) {
let str = `${str[0].toUpperCase()}${str.slice(1)}`;
return str;
// Problem: We can't redeclare 'str' inside the function as it's already a parameter
// Fix: Instead of redeclaring, we just modify the existing 'str' variable directly.

// let str = `${str[0].toUpperCase()}${str.slice(1)} // we should remove the Let

str = `${str[0].toUpperCase()}${str.slice(1)}`;
// Capitalize the first letter and combine with the rest of the string

return str; // Return the modified string
}

console.log(capitalise("coding")); // Expected Output: "Coding"
13 changes: 9 additions & 4 deletions Sprint-2/errors/1.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@
// Why will an error occur when this program runs?
// Try playing computer with the example to work out what is going on

function convertToPercentage(decimalNumber) {
const decimalNumber = 0.5;
const percentage = `${decimalNumber * 100}%`;

// Function to convert decimal to percentage
function convertToPercentage(decimalNumber) {
// const decimalNumber = 0.5;
// Removed the redeclaration of decimalNumber and just use the parameter
const percentage = `${decimalNumber * 100}%`; // Convert the decimal to percentage

return percentage;
}

console.log(decimalNumber);
// Now we pass a decimal number as an argument to the function
console.log(convertToPercentage(0.5)); // Expected Output: "50%"

20 changes: 17 additions & 3 deletions Sprint-2/errors/2.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,22 @@

// this function should square any number but instead we're going to get an error

function square(3) {
return num * num;
}
// function square(3) {
// return num * num;
// }


// The original function is incorrect because:
// 1. The function parameter is written as `3`, which is a value, not a valid parameter name.
// 2. Inside the function, the variable `num` is referenced, but it has not been defined anywhere, causing a ReferenceError.

function square(number) {
// Now, instead of `3`, we have a valid parameter name `number`.
// The function will take `number` as input and return `number * number` (the square of the number).

return number * number; // Multiply the number by itself to square it.
}

// Testing the function by passing the value `3` to it
console.log(square(3)); // Expected Output: 9

Loading