diff --git a/Sprint-3/1-key-errors/0.js b/Sprint-3/1-key-errors/0.js index 653d6f5a0..786b00554 100644 --- a/Sprint-3/1-key-errors/0.js +++ b/Sprint-3/1-key-errors/0.js @@ -1,13 +1,30 @@ // Predict and explain first... // =============> write your prediction here +// My prediction is that the first letter of the string will be capitalized at position 0 because arrays start counting at 0 and slice(1) creates a new string slice starting at position '1' because of the template literals. // 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; +// } + +// console.log(capitalise('rahana')); // =============> write your explanation here +// =============> PREDICTION EXPLANATION: In JavaScript strings are zero-indexed, meaning the first character starts counting at position zero. 'str[0].toUpperCase() aims for the 'r' at position '0' and transforms it to 'R'. The .slice(1) method removes everything from '1' to to the end of the string. By starting at '1', it skips '0' ('r') and gives ('ahana'). the template literals combines 'R' and 'ahana' and adds them together to get('Rahana') +// =============> The SyntaxError: Identifier 'str' has already been declared is occurring because 'str' has already been declared in the function parameter so let has to be named a different. variable(example 'message') so it can return the value of capitalise. +// =============> Alternatively we can remove the let completely and return what is in the template literals. // =============> write your new code here + +// function capitalise(str) { +// let message = `${str[0].toUpperCase()}${str.slice(1)}`; +// return message; +// } + +function capitalise(str) { + return `${str[0].toUpperCase()}${str.slice(1)}`; +} + +console.log(capitalise('rahana')); diff --git a/Sprint-3/1-key-errors/1.js b/Sprint-3/1-key-errors/1.js index f2d56151f..d36b024af 100644 --- a/Sprint-3/1-key-errors/1.js +++ b/Sprint-3/1-key-errors/1.js @@ -1,20 +1,34 @@ // Predict and explain first... +// My prediction: Running this code will result in a SyntaxError because 'decimalNumber' is defined as a parameter in the function declaration, and then re-declared on line 2 using 'const'. In JavaScript, an existing parameter or variable cannot be re-declared in the same scope using 'const' or 'let'. Additionally, calling console.log(decimalNumber) on line 8 will trigger a ReferenceError because 'decimalNumber' is scoped locally to the function and cannot be accessed globally. // Why will an error occur when this program runs? // =============> write your prediction here +// My prediction: A SyntaxError will occur because 'decimalNumber' is automatically declared as a local variable when passed as a function parameter. Declaring it again inside the function body using 'const decimalNumber = 0.5;' breaks JavaScript's re-declaration rules. // Try playing computer with the example to work out what is going on -function convertToPercentage(decimalNumber) { - const decimalNumber = 0.5; - const percentage = `${decimalNumber * 100}%`; +// function convertToPercentage(decimalNumber) { +// const decimalNumber = 0.5; +// const percentage = `${decimalNumber * 100}%`; - return percentage; -} +// return percentage; +// } -console.log(decimalNumber); +// console.log(decimalNumber); // =============> write your explanation here +// =============> Two errors occurred here: +// 1. SyntaxError: 'decimalNumber' is automatically declared as a local variable when passed as a function parameter. Declaring it again inside the function body using 'const decimalNumber = 0.5;' breaks JavaScript's re-declaration rules. +// 2. ReferenceError: I commented out the 'const decimalNumber = 0.5' and got a ReferenceError, this is because 'decimalNumber' only exists within the block scope of the convertToPercentage function. Trying to log console.log(decimalNumber) in the global scope fails because it is not defined out there. +// Solution: Remove 'const decimalNumber = 0.5;' from inside the function body so the parameter can receive the arguments, and call console.log(convertToPercentage(0.7)) instead of logging 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.7)); // output 70% +console.log(convertToPercentage(0.5)); // output 50% diff --git a/Sprint-3/1-key-errors/2.js b/Sprint-3/1-key-errors/2.js index aad57f7cf..6e1ffb842 100644 --- a/Sprint-3/1-key-errors/2.js +++ b/Sprint-3/1-key-errors/2.js @@ -1,20 +1,31 @@ // Predict and explain first BEFORE you run any code... +// Prediction: We will get an error definitely but i'm not sure if it's going to be a ReferenceError or a SyntaxError // 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; -} +// function square(3) { +// return num * num; +// } + +// console.log(square(2)); // =============> write the error message here +// =============> ERROR MESSAGE: SyntaxError: Unexpected number + // =============> explain this error message here +// =============> EXPLANATION: The SyntaxError: Unexpected number happened because the function was expecting an identifier in the parameter ('num') and not a number ('3') which triggered the error + // Finally, correct the code to fix the problem // =============> write your new code here +function square(num) { + return num * num; +} +console.log(square(2)); diff --git a/Sprint-3/2-mandatory-debug/0.js b/Sprint-3/2-mandatory-debug/0.js index b27511b41..5194f8c5c 100644 --- a/Sprint-3/2-mandatory-debug/0.js +++ b/Sprint-3/2-mandatory-debug/0.js @@ -2,13 +2,22 @@ // =============> write your prediction here -function multiply(a, b) { - console.log(a * b); -} +// =============> Prediction: The function will log 320 to the terminal when called, but the template string will evaluate to "The result of multiplying 10 and 32 is undefined" because the function does not return a value but rather '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 -// =============> write your explanation here +// =============> Explanation: When I logged the code in my console, I got this message(The result of multiplying 10 and 32 is undefined). This is because, in JavaScript, every function returns 'undefined' by default unless a 'return' keyword is directly used. Calling console.log() inside a function only outputs to the console without passing a value back. Replacing console.log() with return inside the function body allows the calculated result (320) to be passed directly into the template string. // Finally, correct the code to fix the problem // =============> write your new code here +function multiply(a, b) { + return a * b; +} + +console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); // output 320 \ No newline at end of file diff --git a/Sprint-3/2-mandatory-debug/1.js b/Sprint-3/2-mandatory-debug/1.js index 37cedfbcf..96da0cc3f 100644 --- a/Sprint-3/2-mandatory-debug/1.js +++ b/Sprint-3/2-mandatory-debug/1.js @@ -1,13 +1,26 @@ // Predict and explain first... // =============> write your prediction here -function sum(a, b) { - return; - a + b; -} +// =============> Prediction: Calling sum(10, 32) will return 'undefined', so the console will output "The sum of 10 and 32 is undefined". This is because 'return;' terminates the statement immediately, leaving 'a + b;' as unreachable code. + +// =============> Prediction: The function will evaluate to 'The sum of 10 and 32 is undefined' because there is a semi-colon at the end of the return which ends the statement immediately, leaving 'a + b' with no way of reaching the return statement. -console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); +// function sum(a, b) { +// return; +// a + b; +// } + +// console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); // =============> write your explanation here + +// =============> Explanation: When I run 'console.log(`The sum of 10 and 32 is ${sum(10, 32)}`)', I got this in my terminal 'The sum of 10 and 32 is undefined' because in JavaScript having a semi-colon at the end of a value tells the computer that this statement has ended, treating a + b; as a separate, un-returned statement. To fix this, the expression 'a + b' must sit on the exact same line as 'return'. + // 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)}`); // output The sum of 10 and 32 is 42 \ No newline at end of file diff --git a/Sprint-3/2-mandatory-debug/2.js b/Sprint-3/2-mandatory-debug/2.js index 57d3f5dc3..40c190fe1 100644 --- a/Sprint-3/2-mandatory-debug/2.js +++ b/Sprint-3/2-mandatory-debug/2.js @@ -2,23 +2,44 @@ // Predict the output of the following code: // =============> Write your prediction here +// =============> Prediction: The code will print '3' for all three log statements instead of '2', '5', and '6'. -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 // =============> write the output here + +// =============> Output: 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 + +// =============> Explanation: The function getLastDigit() was defined without parameters, so JavaScript ignored the arguments (42, 105, 806) passed during the function calls. Instead, the function continuously accessed the global variable num (103), converted it to a string, and sliced off the last character ('3') every time. + // Finally, correct the code to fix the problem + +// =============> Fix: Pass a parameter into getLastDigit so it receives the inputs, and use that parameter inside the function body instead of the outer variable. // =============> write your new code here +// const num = 103; + +function getLastDigit(num) { + return num.toString().slice(-1); +} + +console.log(`The last digit of 42 is ${getLastDigit(42)}`); // output The last digit of 42 is 2 +console.log(`The last digit of 105 is ${getLastDigit(105)}`); // output The last digit of 105 is 5 +console.log(`The last digit of 806 is ${getLastDigit(806)}`); // output The last digit of 806 is 6 + // 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-3/3-mandatory-implement/1-bmi.js b/Sprint-3/3-mandatory-implement/1-bmi.js index 58b1085f1..ef4aaa047 100644 --- a/Sprint-3/3-mandatory-implement/1-bmi.js +++ b/Sprint-3/3-mandatory-implement/1-bmi.js @@ -15,5 +15,10 @@ // It should return a string of their Body Mass Index to 1 decimal place function calculateBMI(weight, height) { - // return the BMI of someone based off their weight and height + let bmi = weight / (height ** 2); + return bmi.toFixed(1); + // return Math.round(bmi); } + +console.log(calculateBMI(80, 1.80)); // Output: '24.7' +console.log(calculateBMI(70, 1.73)); // Output: '23.4' diff --git a/Sprint-3/3-mandatory-implement/2-cases.js b/Sprint-3/3-mandatory-implement/2-cases.js index 5b0ef77ad..11bf970a3 100644 --- a/Sprint-3/3-mandatory-implement/2-cases.js +++ b/Sprint-3/3-mandatory-implement/2-cases.js @@ -9,6 +9,13 @@ // When we call this function with the input string // it returns the string in UPPER_SNAKE_CASE, so "HELLO_THERE" +function upperSnakeCase(str) { + return str.toUpperCase().replaceAll(' ', '_'); +} + +console.log(upperSnakeCase('hello world')); // Output: HELLO_WORLD +console.log(upperSnakeCase('lord of the rings')); // Output: LORD_OF_THE_RINGS + // Another example: "lord of the rings" should be "LORD_OF_THE_RINGS" // You will need to come up with an appropriate name for the function diff --git a/Sprint-3/3-mandatory-implement/3-to-pounds.js b/Sprint-3/3-mandatory-implement/3-to-pounds.js index 10754da73..cdb32e65d 100644 --- a/Sprint-3/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-3/3-mandatory-implement/3-to-pounds.js @@ -4,3 +4,27 @@ // 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 toPence(penceString) { + const penceStringWithoutTrailingP = penceString.substring( + 0, + penceString.length - 1, + ); + + const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); + const pounds = paddedPenceNumberString.substring( + 0, + paddedPenceNumberString.length - 2, + ); + + const pence = paddedPenceNumberString + .substring(paddedPenceNumberString.length - 2) + .padEnd(2, "0"); + + return `£${pounds}.${pence}`; +} + +console.log(toPence("399p")); // output £3.99 +console.log(toPence("50p")); // output £0.50 +console.log(toPence("1200p")); // output £12.00 +console.log(toPence("5p")); // output £0.05 diff --git a/Sprint-3/4-mandatory-interpret/time-format.js b/Sprint-3/4-mandatory-interpret/time-format.js index c0dd9c9a5..2854fd50b 100644 --- a/Sprint-3/4-mandatory-interpret/time-format.js +++ b/Sprint-3/4-mandatory-interpret/time-format.js @@ -1,20 +1,22 @@ function pad(num) { - let numString = num.toString(); - while (numString.length < 2) { - numString = "0" + numString; - } - return numString; + let numString = num.toString(); + while (numString.length < 2) { + numString = "0" + numString; + } + return numString; } function formatTimeDisplay(seconds) { - const remainingSeconds = seconds % 60; - const totalMinutes = (seconds - remainingSeconds) / 60; - const remainingMinutes = totalMinutes % 60; - const totalHours = (totalMinutes - remainingMinutes) / 60; + const remainingSeconds = seconds % 60; + const totalMinutes = (seconds - remainingSeconds) / 60; + const remainingMinutes = totalMinutes % 60; + const totalHours = (totalMinutes - remainingMinutes) / 60; - return `${pad(totalHours)}:${pad(remainingMinutes)}:${pad(remainingSeconds)}`; + return `${pad(totalHours)}:${pad(remainingMinutes)}:${pad(remainingSeconds)}`; } +console.log(formatTimeDisplay(61)); + // 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 @@ -23,16 +25,59 @@ function formatTimeDisplay(seconds) { // a) When formatTimeDisplay is called how many times will pad be called? // =============> write your answer here +/* Answer: + The formatTimeDisplay function calls pad three times: + pad(totalHours) + pad(remainingMinutes) + pad(remainingSeconds) + So when formatTimeDisplay is called, pad will be called 3 times. +*/ + // 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 +// =============> Answer: The pad function is called for the first time with the argument totalHours, which is 0. So the value assigned to num when pad is called for the first time is 0. + // c) What is the return value of pad when it is called for the first time? // =============> write your answer here +// =============> Answer: numString = "0" (since 0.toString() is "0"), the while loop checks if "0"length is less than 2, which is true, "0" is padded with a "0" to become "00". So the return value of pad when it is called for the first time is '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 +/* =============> Answer: The formatTimeDisplay function is called with seconds = 61. Inside formatTimeDisplay, these variables are calculated: +remainingSeconds = 61 % 60 = 1 +totalMinutes = (61 - 1) / 60 = 1 +remainingMinutes = 1 % 60 = 1 +totalHours = (1 - 1) / 60 = 0 +The pad function is called three times with the values totalHours (0), remainingMinutes (1), and remainingSeconds (1), in that order. +The order of calls to pad is: +pad(0) (for totalHours) +pad(1) (for remainingMinutes) +pad(1) (for remainingSeconds) +The last call to pad is with the argument remainingSeconds, which is 1. +So, the value assigned to num when pad is called for the last time is 1. +*/ + // e) What is the return value of pad when it is called for the last time in this program? Explain your answer // =============> write your answer here + +/* Answer: +The formatTimeDisplay function is called with seconds = 61. +Inside formatTimeDisplay, these variables are calculated: +remainingSeconds = 61 % 60 = 1 +totalMinutes = (61 - 1) / 60 = 1 +remainingMinutes = 1 % 60 = 1 +totalHours = (1 - 1) / 60 = 0 +The pad function is called three times with the values totalHours (0), remainingMinutes (1), and remainingSeconds (1), in that order. +The last call to pad is pad(1): + +numString = "1" (since 1.toString() is "1"). +The while loop checks if "1".length is less than 2, which is true. +"1" is padded with a "0" to become "01". +The function returns "01". +So, the return value of pad when it's called for the last time is "01". +*/ diff --git a/Sprint-3/5-stretch-extend/format-time.js b/Sprint-3/5-stretch-extend/format-time.js index 32a32e66b..f26482534 100644 --- a/Sprint-3/5-stretch-extend/format-time.js +++ b/Sprint-3/5-stretch-extend/format-time.js @@ -3,23 +3,95 @@ // 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) { + // Extract hours as a Number and minutes as a String const hours = Number(time.slice(0, 2)); - if (hours > 12) { - return `${hours - 12}:00 pm`; + const minutes = time.slice(-2); + + let formattedHours; + let period; + + // Decision Tree for 12-Hour Conversion + if (hours === 0) { + formattedHours = "12"; + period = "am"; + } else if (hours === 12) { + formattedHours = "12"; + period = "pm"; + } else if (hours > 12) { + const twelveHour = hours - 12; + formattedHours = twelveHour < 10 ? `0${twelveHour}` : `${twelveHour}`; + period = "pm"; + } else { + formattedHours = time.slice(0, 2); + period = "am"; } - return `${time} am`; + + // Formatting: Reassemble hours, minutes, and period + return `${formattedHours}:${minutes} ${period}`; } +// Test Cases + const currentOutput = formatAs12HourClock("08:00"); const targetOutput = "08:00 am"; console.assert( currentOutput === targetOutput, - `current output: ${currentOutput}, target output: ${targetOutput}` + `current ${currentOutput}, target ${targetOutput}` ); const currentOutput2 = formatAs12HourClock("23:00"); const targetOutput2 = "11:00 pm"; console.assert( currentOutput2 === targetOutput2, - `current output: ${currentOutput2}, target output: ${targetOutput2}` + `current ${currentOutput2}, target ${targetOutput2}` +); + +const currentOutput3 = formatAs12HourClock("00:00"); +const targetOutput3 = "12:00 am"; +console.assert( + currentOutput3 === targetOutput3, + `current ${currentOutput3}, target ${targetOutput3}` +); + +const currentOutput4 = formatAs12HourClock("01:00"); +const targetOutput4 = "01:00 am"; +console.assert( + currentOutput4 === targetOutput4, + `current ${currentOutput4}, target ${targetOutput4}` ); + +const currentOutput5 = formatAs12HourClock("12:00"); +const targetOutput5 = "12:00 pm"; +console.assert( + currentOutput5 === targetOutput5, + `current ${currentOutput5}, target ${targetOutput5}` +); + +const currentOutput6 = formatAs12HourClock("13:00"); +const targetOutput6 = "01:00 pm"; +console.assert( + currentOutput6 === targetOutput6, + `current ${currentOutput6}, target ${targetOutput6}` +); + +const currentOutput7 = formatAs12HourClock("15:30"); +const targetOutput7 = "03:30 pm"; +console.assert( + currentOutput7 === targetOutput7, + `current ${currentOutput7}, target ${targetOutput7}` +); + +const currentOutput8 = formatAs12HourClock("23:59"); +const targetOutput8 = "11:59 pm"; +console.assert( + currentOutput8 === targetOutput8, + `current ${currentOutput8}, target ${targetOutput8}` +); + +console.log(formatAs12HourClock("00:00")); +console.log(formatAs12HourClock("01:00")); +console.log(formatAs12HourClock("12:00")); +console.log(formatAs12HourClock("13:00")); +console.log(formatAs12HourClock("15:30")); +console.log(formatAs12HourClock("23:59")); +console.log("All assertions completed!");