diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js index 653d6f5a0..36cdb5dc3 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -4,10 +4,25 @@ // 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; -} +// function capitalise(str) { +// let str = `${str[0].toUpperCase()}${str.slice(1)}`; +// return str; +// } // =============> write your explanation here +// The function capitalize is trying to take a string input and return it with the first letter capitalized. +// However, the error occurs because the variable 'str' is being declared twice: once as a parameter and again inside the function. +// This is not allowed in JavaScript, as 'let' does not allow redeclaration of the same variable in the same scope. +// This causes a syntax error because you cannot redeclare a variable with 'let' in the same scope. // =============> write your new code here + +function capitalise(str) { + let name = `${str[0].toUpperCase()}${str.slice(1)}`; + return name; +} +capitalise("hello, check "); +console.log(capitalise("hello, check ")); +// =============> write your explanation here +// The function now uses a different variable name 'name' instead of 'str' inside the function. +// This avoids the redeclaration error. The function takes a string input, capitalizes the first letter, and returns the modified string. +// However, the return statement still returns 'str' instead of 'name', which is a mistake. diff --git a/Sprint-2/1-key-errors/1.js b/Sprint-2/1-key-errors/1.js index f2d56151f..723a872f1 100644 --- a/Sprint-2/1-key-errors/1.js +++ b/Sprint-2/1-key-errors/1.js @@ -5,16 +5,35 @@ // 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; +// The above line will cause an error because 'decimalNumber' is being redeclared with 'const' +// after it has already been defined as a parameter of the function. +// This will result in a SyntaxError: Identifier 'decimalNumber' has already been declared. +// it is trying to declare a new constant variable with the same name as the parameter of the function: decimalNumber +// const percentage = `${decimalNumber * 100}%`; +// The above line correctly converts the decimal number to a percentage by multiplying it by 100 +// and appending a '%' sign. +// However, the function will not execute due to the redeclaration error. -console.log(decimalNumber); +// return percentage; +// // } +// console.log(decimalNumber); +// console.log(decimalNumber) outside the function — but decimalNumber was only defined inside the function. // =============> write your explanation here // Finally, correct the code to fix the problem // =============> write your new code here +function convertToPercentage(decimalNumber) { + const percentage = `${decimalNumber * 100}%`; + return percentage; +} +// =============> write your explanation here +// The function now correctly takes a decimal number as input, converts it to a percentage by multiplying it by 100, +// and returns the result as a string with a '%' sign appended. The redeclaration error has been fixed by removing the +// unnecessary declaration of 'decimalNumber' inside the function. The function can now be called with a decimal number, +// and it will return the corresponding percentage string. +console.log(convertToPercentage(0.5)); // "50%" + +// The function now works correctly and returns the expected output without any errors. diff --git a/Sprint-2/1-key-errors/2.js b/Sprint-2/1-key-errors/2.js index aad57f7cf..84ec2dad9 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -1,20 +1,26 @@ - // Predict and explain first BEFORE you run any code... - +// the will be an error // this function should square any number but instead we're going to get an error +// Why will an error occur when this program runs? +//because the function parameter is incorrectly defined by real number instead of a variable name + // =============> write your prediction of the error here -function square(3) { - return num * num; -} +// function square(3) { +// return num * num; +// } // =============> write the error message here - +//syntaxError: Unexpected number // =============> explain this error message here - +// The error occurs because the function parameter is defined as a number (3) instead of a variable name. +// In JavaScript, function parameters must be variable names, not literal values. JavaScript is expecting a parameter name in the parentheses, not a value. // Finally, correct the code to fix the problem // =============> write your new code here - +function square(num) { + return num * num; +} +console.log(square(3)); // This will not work because 'num' is not defined outside the function diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js index b27511b41..2b688059e 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -1,14 +1,30 @@ // Predict and explain first... +// The code below is intended to multiply two numbers and log the result. +// However, it currently does not return the result correctly. +// The function `multiply` is defined to take two parameters `a` and `b`. +// It logs the product of `a` and `b` but does not return it. +// The console.log statement outside the function attempts to log the result of calling `multiply(10, 32)`. +// The expected output is "The result of multiplying 10 and 32 is 320". +// However, since `multiply` does not return a value, the output will be "The result of multiplying 10 and 32 is undefined". // =============> write your prediction here function multiply(a, b) { - console.log(a * b); + // This function multiplies two numbers and logs the result + // but does not return it. + // It should return the product instead of just logging it. + // The current implementation will not return the product. + //console.log(a * b); + // This line should be changed to return the product + return a * b; // Corrected to return the product } console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); - // =============> write your explanation here +// // The code is intended to multiply two numbers and log the result. +// However, it currently does not return the result correctly. +// The expected output is "The result of multiplying 10 and 32 is 320". +// The current output will be "The result of multiplying 10 and 32 is undefined". // Finally, correct the code to fix the problem // =============> 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..06e6c7e84 100644 --- a/Sprint-2/2-mandatory-debug/1.js +++ b/Sprint-2/2-mandatory-debug/1.js @@ -1,13 +1,20 @@ // Predict and explain first... // =============> write your prediction here +// The sum of 10 and 32 is undefined -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 function called `sum` is defined to take two parameters `a` and `b`, but it does not return the result of adding them together. +// Instead, it has a `return` statement which exits the function without returning any value. // Finally, correct the code to fix the problem // =============> write your new code here +function sum(a, b) { + return a + b; +} +console.log(sum(10, 32)); diff --git a/Sprint-2/2-mandatory-debug/2.js b/Sprint-2/2-mandatory-debug/2.js index 57d3f5dc3..f3d78fc1e 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -1,24 +1,37 @@ // Predict and explain first... +// This code is intended to find the last digit of a number, but it has a bug. // Predict the output of the following code: +// Predict the output of the following code is '3' for the input 103. since the last digit of 103 is 3 and it is a global variable, so regardless of the input, it will always return the last digit of the global variable `num` which is 103. // =============> Write your prediction here -const num = 103; +// const num = 103; -function getLastDigit() { - return num.toString().slice(-1); -} +// 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)}`); +// 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 +// The last digit of 42 is 3 +// The last digit of 105 is 3 +// The last digit of 806 is 3 + // =============> write the output here +// The output is always '3' // Explain why the output is the way it is // =============> write your explanation here +// The output is always '3' because the function `getLastDigit` is using a global variable `num` which is set to 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 diff --git a/Sprint-2/3-mandatory-implement/1-bmi.js b/Sprint-2/3-mandatory-implement/1-bmi.js index 17b1cbde1..9d1d7aa51 100644 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -15,5 +15,15 @@ // It should return their Body Mass Index to 1 decimal place function calculateBMI(weight, height) { - // return the BMI of someone based off their weight and height -} \ No newline at end of file + // return the BMI of someone based off their weight and height + // calculate the height squared + const heightSquared = height * height; + // calculate the BMI + const BMI = weight / heightSquared; + // return the BMI to 1 decimal place + return parseFloat(BMI.toFixed(1)); +} +let weight = 70; // in kg +let height = 1.73; // in meters + +console.log(`BMI is ${calculateBMI(weight, height)}`); diff --git a/Sprint-2/3-mandatory-implement/2-cases.js b/Sprint-2/3-mandatory-implement/2-cases.js index 5b0ef77ad..847a6207c 100644 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -14,3 +14,38 @@ // 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 + +function toUpperSnakeCase(string) { + // First convert the entire string to uppercase + const upperCaseString = string.toUpperCase(); + + // Then split it into words (assuming space-separated) + const wordsArray = upperCaseString.split(" "); + + // Then join the array into a string using underscores + const result = wordsArray.join("_"); + // Return the string in UPPER_SNAKE_CASE + return result; +} +// Example usage for this function +// let string = "hello there"; + +// console.log(`The string in UPPER_SNAKE_CASE is: ${toUpperSnakeCase(string)}`); + +console.log( + `The string in UPPER_SNAKE_CASE for 'hello there' is: ${toUpperSnakeCase( + "hello there" + )}` +); + +console.log( + `The string in UPPER_SNAKE_CASE for 'lord of the rings' is: ${toUpperSnakeCase( + "lord of the rings" + )}` +); + +console.log( + `The string in UPPER_SNAKE_CASE for 'example usage for this function' is: ${toUpperSnakeCase( + "example usage for this function" + )}` +); diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js index 6265a1a70..7f3ee9d2e 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -4,3 +4,32 @@ // 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" from the string + const penceStringWithoutTrailingP = penceString.substring( + 0, + penceString.length - 1 + ); + + // Ensure the number has at least 3 digits by padding from the left with zeros + const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); + + // Extract the pound portion + const pounds = paddedPenceNumberString.substring( + 0, + paddedPenceNumberString.length - 2 + ); + + // Extract the pence portion and pad right if needed + const pence = paddedPenceNumberString + .substring(paddedPenceNumberString.length - 2) + .padEnd(2, "0"); + + // Return the formatted result + return `£${pounds}.${pence}`; +} + +// Example usage: +console.log(toPounds("399p")); +console.log(toPounds("155p")); +console.log(toPounds("75p")); diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js index 7c98eb0e8..1dcb19c4b 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -11,7 +11,7 @@ function formatTimeDisplay(seconds) { 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 +// You will need to play computer with this example - use the Python Visualizer https://pythontutor.com/visualize.html#mode=edit // to help you answer these questions // Questions @@ -20,15 +20,18 @@ function formatTimeDisplay(seconds) { // =============> write your answer here // Call formatTimeDisplay with an input of 61, now answer the following: - +// 3 times which is once each for hours, minutes, and seconds. // b) What is the value assigned to num when pad is called for the first time? // =============> write your answer here - +// 0, because pad is first called with totalHours, which is 0. // c) What is the return value of pad is called for the first time? // =============> write your answer here - +// '00' pad(0) becomes "0" → padded to "00" using padStart(2, "0"). // 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, because the last call to pad is with remainingSeconds, which is 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 +// "01", pad(1) becomes "1" → padded to "01" using padStart(2, "0"). + +// the final output of formatTimeDisplay(61) will be "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..7f223ccb5 100644 --- a/Sprint-2/5-stretch-extend/format-time.js +++ b/Sprint-2/5-stretch-extend/format-time.js @@ -3,23 +3,60 @@ // 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`; + // If hours is less than 12, it should be am + const [hourStr, minute] = time.split(":"); + let hours = Number(hourStr); + let suffix = "am"; + // If hours is 0, it should be 12 am + if (hours === 0) { + hours = 12; } - return `${time} am`; + // If hours is less than 12, it should be am + else if (hours === 12) { + suffix = "pm"; + } + // If hours is greater than 12, it should be pm + else if (hours > 12) { + hours -= 12; + suffix = "pm"; + } + //return `${time} am`; ignoring the actual minutes + const paddedHour = String(hours).padStart(2, "0"); + return `${paddedHour}:${minute} ${suffix}`; } +// test 1 const currentOutput = formatAs12HourClock("08:00"); const targetOutput = "08:00 am"; console.assert( currentOutput === targetOutput, `current output: ${currentOutput}, target output: ${targetOutput}` ); - +// test 2 const currentOutput2 = formatAs12HourClock("23:00"); const targetOutput2 = "11:00 pm"; console.assert( currentOutput2 === targetOutput2, `current output: ${currentOutput2}, target output: ${targetOutput2}` ); +// test3 +const currentOutput3 = formatAs12HourClock("12:00"); +const targetOutput3 = "12:00 pm"; +console.assert( + currentOutput3 === targetOutput3, + `current output: ${currentOutput3}, target output: ${targetOutput3}` +); +//test 4 +const currentOutput4 = formatAs12HourClock("14:45"); +const targetOutput4 = "02:45 pm"; +console.assert( + currentOutput4 === targetOutput4, + `current output: ${currentOutput4}, target output: ${targetOutput4}` +); +// test 5 +const currentOutput5 = formatAs12HourClock("01:00"); +const targetOutput5 = "01:00 am"; +console.assert( + currentOutput5 === targetOutput5, + `current output: ${currentOutput5}, target output: ${targetOutput5}` +);