diff --git a/week-2/debug/0.js b/week-2/debug/0.js index b46d471a..0616d927 100644 --- a/week-2/debug/0.js +++ b/week-2/debug/0.js @@ -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)}`); diff --git a/week-2/debug/1.js b/week-2/debug/1.js index df4020ca..acf27ea4 100644 --- a/week-2/debug/1.js +++ b/week-2/debug/1.js @@ -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)}`); diff --git a/week-2/debug/2.js b/week-2/debug/2.js index bae9652a..446b6f8e 100644 --- a/week-2/debug/2.js +++ b/week-2/debug/2.js @@ -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 + diff --git a/week-2/errors/0.js b/week-2/errors/0.js index 58b1349d..8ad77e9b 100644 --- a/week-2/errors/0.js +++ b/week-2/errors/0.js @@ -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. + + + + + diff --git a/week-2/errors/1.js b/week-2/errors/1.js index 14b5b511..2739d7bb 100644 --- a/week-2/errors/1.js +++ b/week-2/errors/1.js @@ -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. + + + + + diff --git a/week-2/errors/2.js b/week-2/errors/2.js index b0454133..2fc3d04a 100644 --- a/week-2/errors/2.js +++ b/week-2/errors/2.js @@ -1,6 +1,17 @@ // 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) { @@ -8,3 +19,5 @@ function square(3) { } +//Now, you can call this function with a number as an argument, and it will square that number: +console.log(square(5)); // Outputs: 25 diff --git a/week-2/implement/bmi.js b/week-2/implement/bmi.js index 172c7c9a..a192b16c 100644 --- a/week-2/implement/bmi.js +++ b/week-2/implement/bmi.js @@ -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}`); \ No newline at end of file diff --git a/week-2/implement/cases.js b/week-2/implement/cases.js index f66bf7e3..90e92f50 100644 --- a/week-2/implement/cases.js +++ b/week-2/implement/cases.js @@ -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. \ No newline at end of file diff --git a/week-2/implement/to-pounds.js b/week-2/implement/to-pounds.js index 7add3d05..1b5fc218 100644 --- a/week-2/implement/to-pounds.js +++ b/week-2/implement/to-pounds.js @@ -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`); diff --git a/week-2/implement/vat.js b/week-2/implement/vat.js index 44c38d74..26d2a606 100644 --- a/week-2/implement/vat.js +++ b/week-2/implement/vat.js @@ -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}`); diff --git a/week-4/implement/count.test.js b/week-4/implement/count.test.js index 77a713a1..b39d7553 100644 --- a/week-4/implement/count.test.js +++ b/week-4/implement/count.test.js @@ -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. + 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. \ No newline at end of file diff --git a/week-4/implement/get-ordinal-number.test.js b/week-4/implement/get-ordinal-number.test.js index 4e735d0b..a85edfb3 100644 --- a/week-4/implement/get-ordinal-number.test.js +++ b/week-4/implement/get-ordinal-number.test.js @@ -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. + */ +function getOrdinalNumber(n) { + // Implementation of the function goes here +} + +module.exports = getOrdinalNumber; diff --git a/week-4/implement/is-prime.test.js b/week-4/implement/is-prime.test.js index 90199887..416aba51 100644 --- a/week-4/implement/is-prime.test.js +++ b/week-4/implement/is-prime.test.js @@ -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++) { + 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. \ No newline at end of file diff --git a/week-4/implement/password-validator.test.js b/week-4/implement/password-validator.test.js index dfc7cedb..bd02ecdd 100644 --- a/week-4/implement/password-validator.test.js +++ b/week-4/implement/password-validator.test.js @@ -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) { + 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) diff --git a/week-4/implement/repeat.test.js b/week-4/implement/repeat.test.js index 0b2b0a3e..9d363efd 100644 --- a/week-4/implement/repeat.test.js +++ b/week-4/implement/repeat.test.js @@ -23,3 +23,44 @@ // Given a target string str and a negative integer count, // When the repeat function is called with these inputs, // Then it should throw an error or return an appropriate error message, as negative counts are not valid. + +//Defines a function named repeat that takes two parameters, str and count: +function repeat(str, count) { + // Case: Negative Count + if (count < 0) { + throw new Error("Negative count is not valid"); + } + //If the count is negative, it throws an error as negative counts are not valid. + + // Case: Handle Count of 0 + if (count === 0) { + return ""; + //If the count is 0, it returns an empty string. + } + + + // Case: Handle Count of 1 + if (count === 1) { + return str; + //If the count is 1, it returns the original string without repetition. + } + + // Case: Repeat String + return str.repeat(count); + //Uses the repeat method to repeat the string count times and returns the result. +} + +// Test Case 1: Repeat String +const result1 = repeat("abc", 3); +console.log(result1); // Output: "abcabcabc" + +// Test Case 2: Handle Count of 1 +const result2 = repeat("xyz", 1); +console.log(result2); // Output: "xyz" + +// Test Case 3: Handle Count of 0 +const result3 = repeat("123", 0); +console.log(result3); // Output: "" + +// Test Case 4: Negative Count (uncomment the line below to test) +// repeat("test", -2);