diff --git a/Sprint-1/3-mandatory-interpret/3-to-pounds.js b/Sprint-1/3-mandatory-interpret/3-to-pounds.js index 60c9ace69..6d9e74e26 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -25,3 +25,4 @@ console.log(`£${pounds}.${pence}`); // To begin, we can start with // 1. const penceString = "399p": initialises a string variable with the value "399p" + diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js index 653d6f5a0..b95a41047 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -1,13 +1,24 @@ // Predict and explain first... // =============> write your prediction here +// The code will throw an error because the variable 'str' is being redeclared with 'let' inside the function, +// which is not allowed since 'str' is already defined as a parameter of the function. // call the function capitalise with a string input // interpret the error message and figure out why an error is occurring +// function capitalise(str) { +// let str = `${str[0].toUpperCase()}${str.slice(1)}`; +// return str; +// } + +// =============> write your explanation here +// The error occurs because the variable 'str' is being declared again with 'let' inside the function, +// which conflicts with the parameter 'str' that is already defined. In JavaScript, you cannot redeclare a variable with 'let' in the same scope. +// =============> write your new code here function capitalise(str) { - let str = `${str[0].toUpperCase()}${str.slice(1)}`; + str = `${str[0].toUpperCase()}${str.slice(1)}`; return str; } +console.log(capitalise("hello")); // Output: "Hello" + -// =============> write your explanation here -// =============> write your new code here diff --git a/Sprint-2/1-key-errors/1.js b/Sprint-2/1-key-errors/1.js index f2d56151f..2a8efff38 100644 --- a/Sprint-2/1-key-errors/1.js +++ b/Sprint-2/1-key-errors/1.js @@ -2,19 +2,30 @@ // Why will an error occur when this program runs? // =============> write your prediction here +// The code will throw an error 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 // Try playing computer with the example to work out what is going on -function convertToPercentage(decimalNumber) { - const decimalNumber = 0.5; - const percentage = `${decimalNumber * 100}%`; - - return percentage; -} +// function convertToPercentage(decimalNumber) { +// const decimalNumber = 0.5; +// const percentage = `${decimalNumber * 100}%`; -console.log(decimalNumber); +// return percentage; +// } +// console.log(decimalNumber); // =============> write your explanation here +// The error occurs because the variable 'decimalNumber' is being declared again with 'const' inside the function, +// which conflicts with the parameter 'decimalNumber' that is already defined. In JavaScript, // Finally, correct the code to fix the problem // =============> write your new code here +function convertToPercentage(decimalNumber) { + // decimalNumber = 0.5; // Remove 'const' to avoid redeclaration + const percentage = `${decimalNumber * 100}%`; + + return percentage; +} +console.log(convertToPercentage(0.5)); // Output: "50%" +console.log(convertToPercentage(0.1)); // Output: "10%" \ 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..37bc839c6 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -4,17 +4,26 @@ // this function should square any number but instead we're going to get an error // =============> write your prediction of the error here +// The code will throw an error because the function is trying to use a number literal (3) as a parameter name, +// which is not allowed in JavaScript. Function parameters must be valid identifiers, and a number -function square(3) { - return num * num; -} +// function square(3) { +// return num * num; +// } // =============> write the error message here +// SyntaxError: Unexpected number in parameter list // =============> explain this error message here +// The error message indicates that there is a syntax error because the function parameter cannot be a number. +// Function parameters must be valid identifiers, and using a number as a parameter name is not allowed // Finally, correct the code to fix the problem // =============> write your new code here +function square(num) { + return num * num; +} +console.log(square(3)); // Output: 9 diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js index b27511b41..abd468f37 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -1,14 +1,25 @@ // Predict and explain first... // =============> write your prediction here +// This code will not produce the expected string output. Instead, it will: +// Log the result of the multiplication directly (320) +// Then print:The result of multiplying 10 and 32 is undefined -function multiply(a, b) { - console.log(a * b); -} +// function multiply(a, b) { +// console.log(a * b); +// } -console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); +// console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); // =============> write your explanation here +// multiply(10, 32) runs inside the template literal. +// Inside the multiply function, console.log(a * b) prints 320 to the console. +// However, the multiply function does not return a value → so it returns undefined by default. // Finally, correct the code to fix the problem +//You should return the result from the function instead of logging it directly: +function multiply(a, b) { + return a * b; +} +console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); // =============> write your new code here diff --git a/Sprint-2/2-mandatory-debug/1.js b/Sprint-2/2-mandatory-debug/1.js index 37cedfbcf..59fc2e78d 100644 --- a/Sprint-2/2-mandatory-debug/1.js +++ b/Sprint-2/2-mandatory-debug/1.js @@ -1,13 +1,23 @@ // Predict and explain first... // =============> write your prediction here +// This code will output: +// The sum of 10 and 32 is undefined +// because the sum function does not return a value. +// function sum(a, b) { +// return; +// a + b; +// } -function sum(a, b) { - return; - a + b; -} - -console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); +// console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); // =============> write your explanation here +// The sum function does not return a value because the return statement is immediately followed by a semicolon. +// This means the function exits before it can execute the a + b expression. + // Finally, correct the code to fix the problem -// =============> write your new code here +// =============> write your new code here +function sum(a, b) { + return a + b; // Corrected to return the sum of a and b +} +console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); // Output: The sum of 10 and 32 is 42 + diff --git a/Sprint-2/2-mandatory-debug/2.js b/Sprint-2/2-mandatory-debug/2.js index 57d3f5dc3..113c26f53 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -2,23 +2,54 @@ // Predict the output of the following code: // =============> Write your prediction here +// The last digit of 42 is undefined +// The last digit of 105 is undefined +// The last digit of 806 is undefined -const num = 103; -function getLastDigit() { - return num.toString().slice(-1); -} +// const num = 103; -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)}`); +// function getLastDigit() { +// 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)}`); // Now run the code and compare the output to your prediction // =============> write the output here +// The last digit of 42 is undefined +// The last digit of 105 is undefined +// The last digit of 806 is undefined // Explain why the output is the way it is // =============> write your explanation here +// The output is undefined because the getLastDigit function does not accept any parameters. +// It always uses the global variable num, which is set to 103. +// The function getLastDigit should take a number as an argument and return its last digit. + // Finally, correct the code to fix the problem // =============> write your new code here +function getLastDigit(num) { + return num.toString().slice(-1); +} + + // This program should tell the user the last digit of each number. +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)}`); + // Explain why getLastDigit is not working properly - correct the problem +// =============> write your explanation here +// The getLastDigit function is not working properly because it does not accept any parameters. +// It should take a number as an argument and return its last digit. +// The corrected function now accepts a number as an argument and returns its last digit correctly. +// The function now works as intended, returning the last digit of each number passed to it. +// The output will now be: +// The last digit of 42 is 2 +// The last digit of 105 is 5 +// The last digit of 806 is 6 + + diff --git a/Sprint-2/3-mandatory-implement/1-bmi.js b/Sprint-2/3-mandatory-implement/1-bmi.js index 17b1cbde1..c06f31603 100644 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -16,4 +16,18 @@ function calculateBMI(weight, height) { // return the BMI of someone based off their weight and height -} \ No newline at end of file + if (height <= 0) { + throw new Error("Height must be greater than zero."); + } + if (weight <= 0) { + throw new Error("Weight must be greater than zero."); + } + const bmi = weight / (height * height); + return parseFloat(bmi.toFixed(1)); // Return BMI to 1 decimal place +} +// Example usage: + const weight = 70; // in kg + const height = 1.73; // in metres + const bmi = calculateBMI(weight, height); + console.log(`Your BMI is: ${bmi}`); // Output: Your BMI is: 23.4 + diff --git a/Sprint-2/3-mandatory-implement/2-cases.js b/Sprint-2/3-mandatory-implement/2-cases.js index 5b0ef77ad..1cebc7296 100644 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -8,9 +8,26 @@ // Given a string input like "hello there" // When we call this function with the input string // it returns the string in UPPER_SNAKE_CASE, so "HELLO_THERE" +function toUpperSnakeCase(input) { + // Check if input is a string + if (typeof input !== 'string') { + throw new Error("Input must be a string."); + } + // Convert the string to uppercase and replace spaces with underscores + return input.toUpperCase().replace(/ /g, '_'); +} +// Example usage: +const inputString = "hello there"; +const upperSnakeCaseString = toUpperSnakeCase(inputString); +console.log(upperSnakeCaseString); // Output: "HELLO_THERE" // Another example: "lord of the rings" should be "LORD_OF_THE_RINGS" +const inputString1 = "LORD_OF_THE_RINGS"; +const upperSnakeCaseString1 = toUpperSnakeCase(inputString1); +console.log(upperSnakeCaseString1); // Output: "LORD_OF_THE_RINGS" + + // 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 diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js index 6265a1a70..4480e6ff1 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -2,5 +2,24 @@ // You will need to take this code and turn it into a reusable block of code. // 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 + +function toPounds(penceString) { + // Remove the trailing "p" + const penceStringWithoutTrailingP = penceString.slice(0, -1); + + // Pad the string so it's at least 3 digits + const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); + + // Extract pounds and pence + const pounds = paddedPenceNumberString.slice(0, -2); + const pence = paddedPenceNumberString.slice(-2).padEnd(2, "0"); + + return `£${pounds}.${pence}`; +} + +// Test cases +console.log(toPounds("399p")); // £3.99 +console.log(toPounds("99p")); // £0.99 +console.log(toPounds("9p")); // £0.09 +console.log(toPounds("1234p")); // £12.34 \ No newline at end of file diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js index 7c98eb0e8..30b6d0e2e 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -1,6 +1,7 @@ function pad(num) { - return num.toString().padStart(2, "0"); -} + console.log(num); + return num.toString().padStart(2, "0"); +} function formatTimeDisplay(seconds) { const remainingSeconds = seconds % 60; @@ -9,7 +10,7 @@ function formatTimeDisplay(seconds) { const totalHours = (totalMinutes - remainingMinutes) / 60; return `${pad(totalHours)}:${pad(remainingMinutes)}:${pad(remainingSeconds)}`; -} +} // You will need to play computer with this example - use the Python Visualiser https://pythontutor.com/visualize.html#mode=edit // to help you answer these questions @@ -18,17 +19,26 @@ function formatTimeDisplay(seconds) { // a) When formatTimeDisplay is called how many times will pad be called? // =============> write your answer here +// The function formatTimeDisplay will call pad three times: once for totalHours, once for remainingMinutes, and once for remainingSeconds. // Call formatTimeDisplay with an input of 61, now answer the following: // b) What is the value assigned to num when pad is called for the first time? // =============> write your answer here +// The value assigned to num when pad is called for the first time is 0. +// The first call to pad is for totalHours, which is 1. // c) What is the return value of pad is called for the first time? // =============> write your answer here +// The return value of pad when called for the first time is "01". This is because pad converts the number 1 to a string and pads it with a leading zero to ensure it has at least two digits. // 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 +// The value assigned to num when pad is called for the last time is 1. This is because remainingSeconds is calculated as 61 % 60, which equals 1. // 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 +// The return value assigned to num when pad is called for the last time is "01". +// This is because pad converts the number 1 to a string and pads it with a leading zero to ensure it has at least two digits. +// The final output of formatTimeDisplay(61) will be "00:01:01", where each component is padded to two digits. +console.log(formatTimeDisplay(61)); // Output: "00:01:01" diff --git a/Sprint-2/5-stretch-extend/format-time.js b/Sprint-2/5-stretch-extend/format-time.js index 32a32e66b..10cee0e39 100644 --- a/Sprint-2/5-stretch-extend/format-time.js +++ b/Sprint-2/5-stretch-extend/format-time.js @@ -2,24 +2,61 @@ // 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) { +// const hours = Number(time.slice(0, 2)); +// if (hours > 12) { +// return `${hours - 12}:00 pm`; +// } +// return `${time} am`; +// } + +// const currentOutput = formatAs12HourClock("08:00"); +// const targetOutput = "08:00 am"; +// console.assert( +// currentOutput === targetOutput, +// `current output: ${currentOutput}, target output: ${targetOutput}` +// ); + +// const currentOutput2 = formatAs12HourClock("23:00"); +// const targetOutput2 = "11:00 pm"; +// console.assert( +// currentOutput2 === targetOutput2, +// `current output: ${currentOutput2}, target output: ${targetOutput2}` +// ); +// It only handles ":00" times — doesn't process the minutes properly. +// It returns "08:00 am" even though the 08:00 input results in "08:00 am" due to hardcoding the entire string. +// It does not handle: /Midnight (00:00) /Noon (12:00) /Times with non-zero minutes (e.g., 13:45) +// It always appends " am" even if time is 12:00 noon or later. function formatAs12HourClock(time) { - const hours = Number(time.slice(0, 2)); - if (hours > 12) { - return `${hours - 12}:00 pm`; - } - return `${time} am`; + const [hourStr, minuteStr] = time.split(":"); + let hours = Number(hourStr); + const suffix = hours >= 12 ? "pm" : "am"; + + hours = hours % 12; + if (hours === 0) hours = 12; + + const formattedHour = String(hours).padStart(2, "0"); + + return `${formattedHour}:${minuteStr} ${suffix}`; } -const currentOutput = formatAs12HourClock("08:00"); -const targetOutput = "08:00 am"; -console.assert( - currentOutput === targetOutput, - `current output: ${currentOutput}, target output: ${targetOutput}` -); - -const currentOutput2 = formatAs12HourClock("23:00"); -const targetOutput2 = "11:00 pm"; -console.assert( - currentOutput2 === targetOutput2, - `current output: ${currentOutput2}, target output: ${targetOutput2}` -); +// Test cases +const testCases = [ + { input: "08:00", expected: "08:00 am" }, + { input: "23:00", expected: "11:00 pm" }, + { input: "12:00", expected: "12:00 pm" }, + { input: "00:00", expected: "12:00 am" }, + { input: "13:45", expected: "01:45 pm" }, + { input: "11:30", expected: "11:30 am" }, + { input: "15:15", expected: "03:15 pm" }, +]; + +testCases.forEach(({ input, expected }) => { + const output = formatAs12HourClock(input); + console.assert(output === expected, `Test failed for ${input}: got ${output}, expected ${expected}`); +}); + +console.log("✅ All tests completed"); +// This function now correctly formats times in 12-hour clock format, handling edge cases like midnight and noon, and works with any minute value. +// It also passes all the test cases provided, ensuring that it behaves as expected for a variety of inputs. +