diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js index 653d6f5a0..88ab00bda 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -1,5 +1,5 @@ // Predict and explain first... -// =============> write your prediction here +// This code will cause a SyntaxError because the variable `str` is being declared twice within the same function scope. // call the function capitalise with a string input // interpret the error message and figure out why an error is occurring @@ -10,4 +10,13 @@ function capitalise(str) { } // =============> write your explanation here +// Explanation: +// The function parameter is named `str`. Inside the function, the same name `str` is redeclared with `let`. +// JavaScript does not allow redeclaring a variable in the same scope with `let` or `const`, so this causes a SyntaxError. +// The error message would say something like: "Identifier 'str' has already been declared". + // =============> write your new code here +function capitalise(str) { + const result = `${str[0].toUpperCase()}${str.slice(1)}`; + return result; +} \ No newline at end of file diff --git a/Sprint-2/1-key-errors/1.js b/Sprint-2/1-key-errors/1.js index f2d56151f..4bf0010e9 100644 --- a/Sprint-2/1-key-errors/1.js +++ b/Sprint-2/1-key-errors/1.js @@ -1,12 +1,13 @@ -// Predict and explain first... - +// Predict and explain first.:- SyntaxError because the variable 'decimalNumber' is being declared twice // Why will an error occur when this program runs? -// =============> write your prediction here + + // The first decimalNumber is a function parameter and the second decimalNumber is declared using const inside the function body. + //JavaScript does not allow a const or let declaration to reuse the name of a parameter in the same scope. // Try playing computer with the example to work out what is going on function convertToPercentage(decimalNumber) { - const decimalNumber = 0.5; + const decimalNumber= 0.5; const percentage = `${decimalNumber * 100}%`; return percentage; @@ -15,6 +16,17 @@ function convertToPercentage(decimalNumber) { console.log(decimalNumber); // =============> write your explanation here + /*The error happens because the variable name 'decimalNumber' is being used twice in the same function scope: + once as a parameter, and once as a const variable. + note:- JavaScript does not allow redeclaring a parameter name using const or let. + To fix the error, so, we should either rename the internal variable, or just use the parameter directly.*/ // Finally, correct the code to fix the problem -// =============> write your new code here + + +function convertToPercentage(decimalNumber) { + const percentage = `${decimalNumber * 100}%`; + return percentage; +} + +console.log(convertToPercentage(0.5)); \ No newline at end of file diff --git a/Sprint-2/1-key-errors/2.js b/Sprint-2/1-key-errors/2.js index aad57f7cf..49e39c591 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -1,20 +1,22 @@ -// Predict and explain first BEFORE you run any code... +// Predict and explain first BEFORE you run any code:- +// its SyntaxError: Unexpected number because its invalid parameter -// this function should square any number but instead we're going to get an error - -// =============> write your prediction of the error here function square(3) { return num * num; } -// =============> write the error message here +// =============> write the error message :-SyntaxError: Unexpected number -// =============> explain this error message here +// =============> explain this error message here:- its SyntaxError: Unexpected number because the parameter '3' is a number literal, but function parameters must be valid variable names. +// this function should square any number but instead we're going to get an error -// Finally, correct the code to fix the problem -// =============> write your new code here +// Finally, correct the code to fix the problem\ +function square(num) { + return num * num; +} +console.log(square(3)) \ No newline at end of file diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js index b27511b41..528e87be3 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -1,6 +1,6 @@ -// Predict and explain first... - -// =============> write your prediction here +// Predict and explain first:--\ +// The multiply function logs the product of a and b but does not return anything.So the console.log will print: +//The result of multiplying 10 and 32 is undefined function multiply(a, b) { console.log(a * b); @@ -8,7 +8,14 @@ function multiply(a, b) { console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); -// =============> write your explanation here +// he function multiply(a, b) uses console.log to output the product but does not have a return statement. // Finally, correct the code to fix the problem -// =============> write your new code here + + + +function multiply(a, b) { + return a * b; // Return the product instead of logging it +} + +console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); diff --git a/Sprint-2/2-mandatory-debug/1.js b/Sprint-2/2-mandatory-debug/1.js index 37cedfbcf..29109ebd6 100644 --- a/Sprint-2/2-mandatory-debug/1.js +++ b/Sprint-2/2-mandatory-debug/1.js @@ -1,5 +1,6 @@ -// Predict and explain first... -// =============> write your prediction here +// Predict and explain first... +// The function sum(a, b) includes a return statement followed by a line with 'a + b'. +// error:-The sum of a and b is undefined function sum(a, b) { return; @@ -8,6 +9,13 @@ function sum(a, b) { console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); -// =============> write your explanation here +// The return statement ends before 'a + b' due to JavaScript's automatic semicolon insertion. +// As a result, the function returns undefined and 'a + b' is never executed. + // Finally, correct the code to fix the problem -// =============> write your new code here + +function sum(a, b) { + return a + b; +} + +console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); \ No newline at end of file diff --git a/Sprint-2/2-mandatory-debug/2.js b/Sprint-2/2-mandatory-debug/2.js index 57d3f5dc3..246396bbd 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -1,7 +1,10 @@ + // Predict and explain first... // Predict the output of the following code: -// =============> Write your prediction here +//I predict that the output of this code will not be as expected because the variable num has been declared with a value and it cannot be changed because it is a constant variable. +// There is also no parameter in the getLastDigit function. So even though the console.log statements are trying to call the getLastDigit function with different arguments, +// the function will not return any of the sliced version of these values. const num = 103; @@ -14,11 +17,27 @@ console.log(`The last digit of 105 is ${getLastDigit(105)}`); 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 fact that 3 is the result of each console.log statement is because the getLastDigit function is not actually using the arguments of 42, 105, and 806. +Instead, because the num variable was assigned with 103 */ + // Finally, correct the code to fix the problem -// =============> write your new code here +function getLastDigit(num) { + return num.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)}`); // This program should tell the user the last digit of each number. // Explain why getLastDigit is not working properly - correct the problem +/*Originally the getLastDigit function didn't have a parameter to accept an argument, +so it will always use the constant num variable defined at the top of the script to evaluate the last digit. +*/ \ No newline at end of file diff --git a/Sprint-2/3-mandatory-implement/1-bmi.js b/Sprint-2/3-mandatory-implement/1-bmi.js index 17b1cbde1..b0159a37b 100644 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -14,6 +14,13 @@ // Then when we call this function with the weight and height // It should return their Body Mass Index to 1 decimal place -function calculateBMI(weight, height) { +function calculateBMI(weightKg, heightM) { // return the BMI of someone based off their weight and height -} \ No newline at end of file + const square=(heightM*heightM); + const bmi = weightKg / square; + // return the BMI to 1 decimal + return bmi.toFixed(1); + +} +console.log(`The BMI of a person with a weight of 70kg and a height of 1.73m is ${calculateBMI(70, 1.73 )}`); +// logs "The BMI of a person with a weight of 70kg and a height of 1.73m is 23.4" to the console. diff --git a/Sprint-2/3-mandatory-implement/2-cases.js b/Sprint-2/3-mandatory-implement/2-cases.js index 5b0ef77ad..65d682911 100644 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -14,3 +14,14 @@ // You will need to come up with an appropriate name for the function // Use the MDN string documentation to help you find a solution // This might help https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase + +/* I create a function named strToUppersnakeCase that replaces spaces with underscores, + and then call the function in the console to print the result */ + + function strToUppersnakeCase(str) { + return str.toUpperCase().replace(/\s+/g, "_"); +} + +// Calling the function and printing the result in the console +console.log(strToUppersnakeCase("hello there")); +console.log(strToUppersnakeCase("lord of the rings")); diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js index 6265a1a70..95f91ed1b 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -4,3 +4,45 @@ // You will need to declare a function called toPounds with an appropriately named parameter. // You should call this function a number of times to check it works for different inputs + +/*const penceString = "399p";// Initializes the string and extracts all characters except the trailing 'p' +const penceStringWithoutTrailingP = penceString.substring(0,penceString.length - 1); +const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); +const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2); // Extracts the pounds part by taking all digits except the last two +const pence = paddedPenceNumberString.substring(paddedPenceNumberString.length - 2).padEnd(2, "0"); // Extracts the pence portion of the price by taking the last two digits and ensures it has exactly two digits. +console.log(`£${pounds}.${pence}`); */ + +function toPounds(pence) { + if (typeof pence !== "string" || !pence.endsWith("p")) { + return "Invalid input. The input must be a string ending with 'p'."; + } + + const penceStringWithoutTrailingP = pence.substring(0, pence.length - 1); + const penceNumber = Number(penceStringWithoutTrailingP); + + if (Number.isInteger(penceNumber) && penceNumber >= 0) { + const paddedPenceNumberString = penceStringWithoutTrailingP.padStart( + 3, + "0" + ); + const pounds = paddedPenceNumberString.substring( + 0, + paddedPenceNumberString.length - 2 + ); + + const pennies = paddedPenceNumberString + .substring(paddedPenceNumberString.length - 2) + .padEnd(2, "0"); + + return `£${pounds}.${pennies}`; + } else { + return "Invalid input. The pence amount must be in number format and must be whole numbers that are not less than 0"; + } +} + +console.log(toPounds("5498p")); //result is £54.98 +console.log(toPounds("63p")); //result is £0.63 +console.log(toPounds("5498")); //result is "Invalid input. The input must be a string ending with 'p'." +console.log(toPounds("-99p")); //result is "Invalid input. The pence amount must be in number format and must be whole numbers that are not less than 0" +console.log(toPounds("pp")); //result is "Invalid input. The pence amount must be in number format and must be whole numbers that are not less than 0" +console.log(toPounds("12.7p")); //Invalid input. The pence amount must be in number format and must be whole numbers that are not less than 0 diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js index 7c98eb0e8..8e6d6b24e 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -17,18 +17,29 @@ function formatTimeDisplay(seconds) { // Questions // a) When formatTimeDisplay is called how many times will pad be called? -// =============> write your answer here +// 3 times + //(Once each for totalHours, remainingMinutes, and remainingSeconds) + + // Call formatTimeDisplay with an input of 61, now answer the following: +//console.log(formatTimeDisplay(61)); //result is "00:01:01" // b) What is the value assigned to num when pad is called for the first time? -// =============> write your answer here +// 0 + //(The value of totalHours) + + // c) What is the return value of pad is called for the first time? -// =============> write your answer here +// "00" +//(0.toString().padStart(2, "0") → "00") // d) What is the value assigned to num when pad is called for the last time in this program? Explain your answer -// =============> write your answer here +// 1 +//The value assigned to num when pad is called for the last time is 1. This is because the function takes an input of 61 +// and the remainingSeconds variable takes the remainder when 61 is divided by 60 .or in other words the number of seconds left after dividing 61 seconds into full minutes // e) What is the return value assigned to num when pad is called for the last time in this program? Explain your answer -// =============> write your answer here +// "01" +//(1.toString().padStart(2, "0") → "01") diff --git a/Sprint-2/5-stretch-extend/format-time.js b/Sprint-2/5-stretch-extend/format-time.js index 32a32e66b..ad16b1362 100644 --- a/Sprint-2/5-stretch-extend/format-time.js +++ b/Sprint-2/5-stretch-extend/format-time.js @@ -2,24 +2,109 @@ // Make sure to do the prep before you do the coursework // Your task is to write tests for as many different groups of input data or edge cases as you can, and fix any bugs you find. -function formatAs12HourClock(time) { +/*function formatAs12HourClock(time) { const hours = Number(time.slice(0, 2)); if (hours > 12) { return `${hours - 12}:00 pm`; } return `${time} am`; } + */ +/*in this code ,many different groups of input data or edge cases, and fix any bugs- Always returns :00 minutes for PM values, even if actual minutes are not 00 +and "08:00 am" directly from the input for 08:00,and not clearly mention 12:00 (should be 12:00 pm, not 12:00 am) ,00:00 (should be 12:00 am, not 00:00 am) +*/ +function formatAs12HourClock(time) { + const [hourStr, minuteStr] = time.split(":"); + let hours = Number(hourStr); + const period = hours >= 12 ? "pm" : "am"; +if (hours === 0) { + hours = 12; + } else if (hours > 12) { + hours -= 12; + } + + return `${hours}:${minuteStr} ${period}`; +} +/*The function `formatAs12HourClock` converts a 24-hour time string like `"23:00"` into a 12-hour format with AM or PM. First, it splits the input string at the colon, separating the hours and minutes into two variables, for example, `"23"` and `"00"`. +The hour string is then converted to a number so it can be manipulated. The minutes remain as a string. +Next, the function determines whether the time is AM or PM by checking if the hour is 12 or more; if so, it sets the period to "pm", otherwise to "am". There’s a special case for midnight: if the hour is 0, it is changed to 12 because 12:00 am represents midnight in 12-hour time. +If the hour is greater than 12, the function subtracts 12 to convert it to the appropriate 12-hour value (e.g., 23 becomes 11). Finally, it returns a formatted string combining the converted hour, the original minutes, and the correct period, such as `"11:00 pm"` or `"12:00 am"`. +*/ + + -const currentOutput = formatAs12HourClock("08:00"); -const targetOutput = "08:00 am"; -console.assert( - currentOutput === targetOutput, - `current output: ${currentOutput}, target output: ${targetOutput}` +const currentOutput1 = formatAs12HourClock("08:00"); +const targetOutput1 = "8:00 am"; +console.assert(currentOutput1 === targetOutput1, + `Test 1 Failed: current output: ${currentOutput1}, target output: ${targetOutput1}` ); const currentOutput2 = formatAs12HourClock("23:00"); const targetOutput2 = "11:00 pm"; -console.assert( - currentOutput2 === targetOutput2, - `current output: ${currentOutput2}, target output: ${targetOutput2}` +console.assert(currentOutput2 === targetOutput2, + `Test 2 Failed: current output: ${currentOutput2}, target output: ${targetOutput2}` +); + +const currentOutput3 = formatAs12HourClock("00:00"); +const targetOutput3 = "12:00 am"; +console.assert(currentOutput3 === targetOutput3, + `Test 3 Failed: current output: ${currentOutput3}, target output: ${targetOutput3}` +); + +const currentOutput4 = formatAs12HourClock("10:00"); +const targetOutput4 = "10:00 am"; +console.assert(currentOutput4 === targetOutput4, + `Test 4 Failed: current output: ${currentOutput4}, target output: ${targetOutput4}` +); + +const currentOutput5 = formatAs12HourClock("11:00"); +const targetOutput5 = "11:00 am"; +console.assert(currentOutput5 === targetOutput5, + `Test 5 Failed: current output: ${currentOutput5}, target output: ${targetOutput5}` ); + +const currentOutput6 = formatAs12HourClock("12:00"); +const targetOutput6 = "12:00 pm"; +console.assert(currentOutput6 === targetOutput6, + `Test 6 Failed: current output: ${currentOutput6}, target output: ${targetOutput6}` +); + +const currentOutput7 = formatAs12HourClock("12:30"); +const targetOutput7 = "12:30 pm"; +console.assert(currentOutput7 === targetOutput7, + `Test 7 Failed: current output: ${currentOutput7}, target output: ${targetOutput7}` +); + +const currentOutput8 = formatAs12HourClock("00:01"); +const targetOutput8 = "12:01 am"; +console.assert(currentOutput8 === targetOutput8, + `Test 8 Failed: current output: ${currentOutput8}, target output: ${targetOutput8}` +); + +const currentOutput9 = formatAs12HourClock("13:15"); +const targetOutput9 = "1:15 pm"; +console.assert(currentOutput9 === targetOutput9, + `Test 9 Failed: current output: ${currentOutput9}, target output: ${targetOutput9}` +); + +const currentOutput10 = formatAs12HourClock("01:59"); +const targetOutput10 = "1:59 am"; +console.assert(currentOutput10 === targetOutput10, + `Test 10 Failed: current output: ${currentOutput10}, target output: ${targetOutput10}` +); + +console.log("All tests passed successfully."); + +/*I created a set of test cases to check whether the formatAs12HourClock function works correctly for various types of 24-hour time inputs. +Each test checks if the function returns the correct 12-hour format with the right hour, minutes, and AM/PM suffix. + +including:- +Regular morning times like "08:00" → "8:00 am" +Midnight ("00:00") → "12:00 am" +Noon ("12:00") → "12:00 pm" +Afternoon and evening times like "13:15" → "1:15 pm" and "23:00" → "11:00 pm" +Minute-specific checks like "12:30" and "00:01" to confirm that the minute part is preserved correctly +Early morning edge cases like "01:59" +Each test uses console.assert() to compare the actual output with the expected result, and if any test fails, it prints a clear error message. If all tests pass, it prints "All tests passed successfully. +This helps confirm the function handles both common cases and edge cases correctly. + */