Skip to content
This repository was archived by the owner on Apr 18, 2025. It is now read-only.

NW6 | Nazanin_Saedi| Module-JS1 | WEEK4 #182

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
12 changes: 12 additions & 0 deletions week-2/debug/0.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,15 @@ function multiply(a, b) {
}

console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`);

// In the provided code snippet, there is a function called multiply that takes two parameters,
// a and b, and multiplies them together. The result of the multiplication is then logged to the
// console using console.log(a * b).
// after defining the multiply function,
// there is a console.log statement that attempts to log the result of multiplying 10 and 32 using the multiply function.
// However, there is a potential issue in the way the console.log statement is structured.
function multiply(a, b) {
return a * b;
}

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

console.log(`The sum of 10 and 32 is ${sum(10, 32)}`);



// In the provided code snippet, there is a function called sum that takes two parameters,
// a and b. However, there is an issue with the return statement in the function.
// The return statement is followed by a line of code a + b;,
// but this line of code will not be executed because the return statement ends the function execution and returns control to the calling context.
// Therefore, the a + b; line is essentially unreachable code.
// Additionally, the return statement itself does not have any value associated
// with it (i.e., it is return;), so the function will implicitly return undefined.
// As a result, when you call sum(10, 32) and try to interpolate the result into
// the template string in the console.log statement, it will display:
// The sum of 10 and 32 is undefined
// To fix this issue and correctly calculate the sum, you should remove
// the return; statement and directly return the result of the addition:

function sum(a, b) {
return a + b;
}

console.log(`The sum of 10 and 32 is ${sum(10, 32)}`);
28 changes: 26 additions & 2 deletions week-2/debug/2.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,32 @@ function getLastDigit() {
}

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)}`);
// In this line, getLastDigit is called, but it doesn't use the argument 42.
// It always operates on the global constant num, which is 103.
// Therefore, it will correctly output the last digit of 103, not 42.
// To fix this issue, you should modify the getLastDigit function to accept
// a parameter and use that parameter instead of the global constant num:
// function getLastDigit(number) {
// return number.toString().slice(-1);
// }

// 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)}`);


console.log(`The last digit of 105 is ${getLastDigit(105)}`);
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

// Now, the function will correctly operate on the provided arguments,
// and the output will be as expected:
// The last digit of 42 is 2
// The last digit of 105 is 5
// The last digit of 806 is 6

28 changes: 28 additions & 0 deletions week-2/errors/0.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,31 @@ function capitalise(str) {
let str = `${str[0].toUpperCase()}${str.slice(1)}`;
return str;
}



// Predicted Error:
// I expect that there will be an error related to the redeclaration of the variable str within the function.
// JavaScript does not allow redeclaration of variables using the let keyword in the same scope.
// Now, let's call the capitalise function:
// capitalise("example");
// Interpretation of the Error (if prediction was correct):
// The error message would likely be something like "Identifier 'str' has already been declared"
// because the variable str is being declared again in the function,
// and it's in the same scope as the function parameter.
// The variable name str is used for both the function parameter and the local variable,
// causing a conflict.

// Corrected Version:
// To fix this issue, you should use a different variable name for the local variable inside the function, like this:

function capitalise(str) {
let capitalizedStr = `${str[0].toUpperCase()}${str.slice(1)}`;
return capitalizedStr;
}
//This way, there won't be a redeclaration conflict, and the function should work correctly.





30 changes: 30 additions & 0 deletions week-2/errors/1.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,33 @@ function convertToPercentage(decimalNumber) {
}

console.log(decimalNumber);


// Predicted Error:
// I predict that there will be a reference error indicating that decimalNumber is not defined
// when the console.log(decimalNumber); statement is executed.

// Explanation of the Error:
// The decimalNumber variable is declared as a parameter of the convertToPercentage function.
// However, within the function, a new constant decimalNumber is declared and initialized with the value 0.5.
// This new declaration creates a local variable that shadows the function parameter.
// When the console.log(decimalNumber); statement is executed outside the function,
// it is referencing the global scope where decimalNumber is not defined.
// The local variable declared within the function does not exist outside of that function's scope.
// To fix this issue, you should remove the redundant declaration of decimalNumber within the function:
function convertToPercentage(decimalNumber) {
const percentage = `${decimalNumber * 100}%`;
return percentage;
}

console.log(convertToPercentage(0.5));


// Now, the function takes the decimalNumber as a parameter,
// and you can pass a value when calling the function.
// The console.log statement at the end correctly logs the result of the function call.





13 changes: 13 additions & 0 deletions week-2/errors/2.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,23 @@

// Predict and explain first...
// unction parameters should be specified by their names,
// not by values or literals. So, function square(3) is not a valid function declaration.

// this function should square any number but instead we're going to get an error
//The syntax for declaring a function includes naming the parameters, and it should look like this:
function square(num) {
return num * num;
}
//3 is not a valid parameter name



// what is happening? How can we fix it?

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


//Now, you can call this function with a number as an argument, and it will square that number:
console.log(square(5)); // Outputs: 25
12 changes: 12 additions & 0 deletions week-2/implement/bmi.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,15 @@
// Given someone's weight in kg and height in metres
// When we call this function with the weight and height
// Then it returns their Body Mass Index to 1 decimal place

function calculateBMI(weight, height) {
const bmi = weight / (height * height);
const roundedBMI = parseFloat(bmi.toFixed(1));
return roundedBMI;
}

const weight = 70; // in kilograms
const height = 1.73; // in meters

const bmiResult = calculateBMI(weight, height);
console.log(`The BMI is: ${bmiResult}`);
29 changes: 29 additions & 0 deletions week-2/implement/cases.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,32 @@

// Come up with a clear, simple name for the function
// Use the string documentation to help you plan your solution

// **** Let's create a function called convertToUpperCaseWithUnderscores that takes a string as
// input and returns the string in UPPER_SNAKE_CASE:
/**
* Converts a given string to UPPER_SNAKE_CASE.
* @param {string} inputString - The input string to be converted.
* @returns {string} The input string in UPPER_SNAKE_CASE.
*/
function convertToUpperCaseWithUnderscores(inputString) {
// Split the input string into an array of words
const words = inputString.split(" ");

// Capitalize each word and join them with underscores
const upperSnakeCaseString = words.map(word => word.toUpperCase()).join("_");

return upperSnakeCaseString;
}

// Test cases
console.log(convertToUpperCaseWithUnderscores("lord of the rings")); // Output: "LORD_OF_THE_RINGS"
console.log(convertToUpperCaseWithUnderscores("the great gatsby")); // Output: "THE_GREAT_GATSBY"
console.log(convertToUpperCaseWithUnderscores("the da vinci code")); // Output: "THE_DA_VINCI_CODE"

// In this function:

// The split(" ") method is used to split the input string into an array of words.
// The map function is used to capitalize each word with toUpperCase().
// The join("_") method is used to join the capitalized words with underscores.
// The resulting string is returned in UPPER_SNAKE_CASE.
25 changes: 25 additions & 0 deletions week-2/implement/to-pounds.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,28 @@
// Take this code and turn it into a reusable block of code.
// Declare a function called toPounds with an appropriately named parameter.
// Call this function a number of times to check it works for different inputs

// Define the toPounds function
function toPounds(amountInKilograms) {
// Conversion factor from kilograms to pounds
const poundsPerKilogram = 2.20462;

// Perform the conversion
const amountInPounds = amountInKilograms * poundsPerKilogram;

// Return the result
return amountInPounds;
}

// Example usage of the toPounds function
const kilograms1 = 5;
const pounds1 = toPounds(kilograms1);
console.log(`${kilograms1} kilograms is equal to ${pounds1} pounds`);

const kilograms2 = 10;
const pounds2 = toPounds(kilograms2);
console.log(`${kilograms2} kilograms is equal to ${pounds2} pounds`);

const kilograms3 = 2.5;
const pounds3 = toPounds(kilograms3);
console.log(`${kilograms3} kilograms is equal to ${pounds3} pounds`);
20 changes: 20 additions & 0 deletions week-2/implement/vat.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,23 @@
// Given a number,
// When I call this function with a number
// Then it returns the new price with VAT added on

function calculatePriceWithVAT(originalPrice) {
// VAT rate (20%)
const vatRate = 0.2;

// Calculate the new price with VAT
const newPrice = originalPrice * (1 + vatRate);

// Return the result
return newPrice;
}

// Example usage
const originalPrice1 = 50;
const newPrice1 = calculatePriceWithVAT(originalPrice1);
console.log(`Original price: £${originalPrice1}, New price with VAT: £${newPrice1}`);

const originalPrice2 = 75;
const newPrice2 = calculatePriceWithVAT(originalPrice2);
console.log(`Original price: £${originalPrice2}, New price with VAT: £${newPrice2}`);
38 changes: 38 additions & 0 deletions week-4/implement/count.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,41 @@
// And a character char that does not exist within the case-sensitive str,
// When the function is called with these inputs,
// Then it should return 0, indicating that no occurrences of the char were found in the case-sensitive str.
function countChar(str, char) {
// Initialize a counter to keep track of occurrences
let count = 0;

// Loop through each character in the string
for (let i = 0; i < str.length; i++) {
// Check if the current character matches the specified character
if (str[i] === char) {
// Increment the counter if there is a match
count++;

// Additional logic to handle consecutive occurrences
// For example, if char is 'a' and str is 'aaaaa',
// we want to count this as one occurrence of 'a'.
// So, we can skip consecutive occurrences by incrementing i until a different character is encountered.
Copy link

Choose a reason for hiding this comment

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

This works but is not what the question asked for I'm afraid - please read the instructions again and tweak it

while (i + 1 < str.length && str[i + 1] === char) {
i++;
}
}
}

// Return the final count of occurrences
return count;
}

// Example Usage:
const str1 = "aaaaa";
const char1 = "a";
console.log(countChar(str1, char1)); // Output: 5

const str2 = "Hello, World!";
const char2 = "z";
console.log(countChar(str2, char2)); // Output: 0


// This implementation checks each character in the string and increments the count whenever
// it finds a match with the specified character. It also handles consecutive occurrences by
// skipping them and only counting them once. If no occurrences are found, it returns 0.
15 changes: 15 additions & 0 deletions week-4/implement/get-ordinal-number.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,18 @@

// continue testing and implementing getOrdinalNumber for additional cases
// Write your tests using Jest - remember to run your tests often for continual feedback

// Assuming your getOrdinalNumber function is designed to take an integer as input and
// return its ordinal representation (e.g., 1st, 2nd, 3rd, etc.), here are some test cases:
// getOrdinalNumber.js

/**
* Function to get the ordinal representation of a number.
* @param {number} n - The input number.
* @returns {string} - The ordinal representation of the input number.
*/
Copy link

Choose a reason for hiding this comment

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

Need to finish this

function getOrdinalNumber(n) {
// Implementation of the function goes here
}

module.exports = getOrdinalNumber;
26 changes: 26 additions & 0 deletions week-4/implement/is-prime.test.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,29 @@
// Given a positive integer num,
// When the isPrime function is called with num as input,
// Then it should return a boolean representing whether the num is prime

//a function named isPrime that takes a parameter num.

function isPrime(num) {
// If the number is less than 2, it's not prime
//If the input number num is less than 2, it's not a prime number, so the function returns false.
if (num < 2) {
return false;
}
//The function uses a for loop to iterate from 2 to the square root of num.
// Inside the loop, it checks if num is divisible by the current value of i.
// If it is divisible, the function returns false, indicating that the number is not prime.

// Check for divisibility from 2 to the square root of the number
for (let i = 2; i <= Math.sqrt(num); i++) {
Copy link

Choose a reason for hiding this comment

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

This works, but it is quite complicated - are you confident in your understanding?

if (num % i === 0) {
// If the number is divisible by any other number, it's not prime
return false;
}
}

// (If no divisor is found, the number is prime)
return true;
}
//If the loop completes without finding any divisor, the function returns true,
//indicating that the number is prime.
21 changes: 21 additions & 0 deletions week-4/implement/password-validator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,24 @@ To be valid, a password must:

You must breakdown this problem in order to solve it. Find one test case first and get that working
*/


// Defines a function named isPasswordValid that takes a parameter password.
function isPasswordValid(password) {
// Step 1: Check if the password has at least 5 characters
if (password.length < 5) {
Copy link

Choose a reason for hiding this comment

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

Looks good, need to impliment the rest

return false;
}
//If the length of the password is less than 5,
//the function returns false, indicating that the password is not valid.

return true;
// If the password passes all the checks, return true
}
// If the password passes all the checks (we only have one check for now),
// the function returns true.

// Test case
const testPassword = "abcde";
const result = isPasswordValid(testPassword);
console.log(result); // Output: false (because "abcde" has less than 5 characters)
Loading