diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js index 653d6f5a0..434814849 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -1,13 +1,41 @@ // Predict and explain first... -// =============> write your prediction here +// I predict when this code runs, there will be a SyntaxError before the function executes. +// This is because the identifier 'str' has already been declared. // call the function capitalise with a string input +// capitalise("hello"); + + // interpret the error message and figure out why an error is occurring +// Uncaught SyntaxError: Unexpected identifier 'string' - this is the error message. +// This error is occuring because the variable 'str' is being redeclared within the function, which is not allowed in JavaScript. +// The duplicate use if 'str' is causing the syntax error. + + +//function capitalise(str) { + //let str = `${str[0].toUpperCase()}${str.slice(1)}`; + //return str; +//} + +// The issue is variable redeclaration. +// str is the function parameter. +// let str tries to create a new variable with the same name. +// JavaScript does not allow redeclaring a variable in the same scope. +// As a result, the code throws a SyntaxError when it encounters the second 'str' declaration. +// New code without the error: + +// 0.js — fully fixed version function capitalise(str) { - let str = `${str[0].toUpperCase()}${str.slice(1)}`; - return str; + if (!str) return str; // handles empty string + return str[0].toUpperCase() + str.slice(1); } -// =============> write your explanation here -// =============> write your new code here +// Test it +console.log(capitalise("hello")); // should print "Hello" +console.log(capitalise("world")); // should print "World" +console.log(capitalise("")); // should print "" + + + + diff --git a/Sprint-2/1-key-errors/1.js b/Sprint-2/1-key-errors/1.js index f2d56151f..1c0cbb33c 100644 --- a/Sprint-2/1-key-errors/1.js +++ b/Sprint-2/1-key-errors/1.js @@ -1,20 +1,29 @@ // Predict and explain first... - // Why will an error occur when this program runs? -// =============> write your prediction here +// I predict an error will occur when this program runs because the variable 'decimalNumber' is already declared inside the function 'convertToPercentage' and cannot be redeclared. // Try playing computer with the example to work out what is going on +// When the 'function convertToPercentage(decimalNumber)' is created, Javascript already creates a variable called decimalNumber. then, inside the function, 'const decimalNumber = 0.5' tries to create another variable with the same name. This casues a syntax error because you cannot declare two variables with the same name in the same scope. -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 +// Write your explanation here +// I redelcared the parameter decimalNumber using const. +// I tried to log decimalNumber outside its scope. +// The variables declared inside the function are not available outside unless they are returned. // 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)); // "50%" diff --git a/Sprint-2/1-key-errors/2.js b/Sprint-2/1-key-errors/2.js index aad57f7cf..a6183a5c6 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -1,20 +1,32 @@ // Predict and explain first BEFORE you run any code... +// This function should square any number but instead we're going to get an error -// this function should square any number but instead we're going to get an error +// Write your prediction of the error here: +// I predict that the error will be a syntax error because the parameter '3' is not a valid variable name. +// When you define a function,, the thing inside the parentahese must be a parameter name, NOT a number. -// =============> 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 -// =============> write the error message here - -// =============> explain this error message here +// Explain the error messge here: +// When defining a function, inside the parentheses, you need to put a parameter name, which is a variable. +// In this case, '3' is not a valid parameter name because it is a number, not a variable. +// This causes a syntax error because Javascript expects a name, not a number. // Finally, correct the code to fix the problem +// Write your new code here + +function square(num) { + return num * num; +} + +console.log(square(3)); // 9 +console.log(square(5)); // 25 -// =============> write your new code here diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js index b27511b41..51ce1ba85 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -1,14 +1,24 @@ -// Predict and explain first... +// Predict and explain first...write your prediction here +// I predict, when the code runs, it will print 320, but it will also print "The result of multiplying 10 and 32 is undefined". -// =============> write your prediction here +//function multiply(a, b) { +// console.log(a * b); +// } + +// console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); + +// Write your explanation here +// The function multiply(a, b) logs the result of a * b to the console but does not return a value. +// When multiply(10, 32) is called within the template literal, it logs 320 to the console but returns undefined. +// Therefore, inside the template literal, the value is undefined, which is why the final output becomes "The result of multiplying 10 and 32 is undefined". + +// Finally, correct the code to fix the problem +// Write your new code here +// To fix the problem, the function should return the result instead of logging it. function multiply(a, b) { - console.log(a * b); + return a * b; } console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); -// =============> write your explanation here - -// 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..97b068aba 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 +// Predict and explain first...write your prediction here +// I think the code will return 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 +// When JavaScript sees the 'return' statement, it immediately stopd the function. It does NOT continue to the next line. +// So this part, 'a+b;' never runs. To return the sum of a and b, we need to put it on the same line as the return. +// Like the: 'return a + b;' -// =============> write your explanation here // 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)}`); diff --git a/Sprint-2/2-mandatory-debug/2.js b/Sprint-2/2-mandatory-debug/2.js index 57d3f5dc3..1819a950d 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -1,24 +1,43 @@ // Predict and explain first... // Predict the output of the following code: -// =============> Write your prediction here +// Write your prediction here +// I think the output will be 'The last digit of 42 is 2', 'The last digit of 105 is 5', and 'The last digit of 806 is 6'. +// I think this will happen because the getLastDigit function is supposed to take a number, convert it to a string, and then return the last charecter of that string, which should be the last digit. -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)}`); + +// Now run the code and compare the output to your prediction +// Write the output here +// The output is: +// 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 output is 3 for all numbers because the function getLastDigit is not taking any parameters. It always uses the global variable `num` which is set to 103. So it always returns the last digit of 103, which is 3. + +// Finally, correct the code to fix the problem +// Write your new code here + +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)}`); -// Now run the code and compare the output to your prediction -// =============> write the output here -// Explain why the output is the way it is -// =============> write your explanation here -// Finally, correct the code to fix the problem -// =============> write your new code here // This program should tell the user the last digit of each number. // Explain why getLastDigit is not working properly - correct the problem +// The function did not accept a parameter. It was a fixed variable (num = 103), so it always returned the last digit of 103. \ 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..c2b35cc71 100644 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -14,6 +14,30 @@ // 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(weight, height) { // return the BMI of someone based off their weight and height -} \ No newline at end of file +// } + +// Notes: +// BMI = weight ÷ (height x height) +// eg. BMI = 70kg ÷ (1.73m x 1.73) +// BMI = 70kg ÷ 2.99 +// BMI = 23.41 +// BMI = 23.4 (to 1 decimal place) + +// I need to: +// 1. Square the height +// 2. Divide weight by squared height +// 3. Round the result to 1 decimal place +// 4. Return the result + +function calculateBMI(weight, height) { + const bmi = weight / (height * height); + return bmi.toFixed(1); +} + +console.log(calculateBMI(70, 1.73)); + + + +//toFixed(1) tells JavaScript to round the number to 1 decimal place. \ No newline at end of file diff --git a/Sprint-2/3-mandatory-implement/2-cases.js b/Sprint-2/3-mandatory-implement/2-cases.js index 5b0ef77ad..180b793b5 100644 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -14,3 +14,24 @@ // 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 + +// NOTES: +// "hello there" should become "HELLO_THERE" +// I need to turn all letters into CAPITALS and replace the space " " with underscore "-" + +// From the MDN documentation: +// I can use the toUpperCase() to turn the tring into all CAPS. +// I can use the replaceAll() to replace all the spaces with underscores. + +// Good function name: +// toUpperSnakeCase - this name is decriptive and indicates that the function will convert a string to upper snake case. + +function toUpperSnakeCase(str) { + return str.toUpperCase().replaceAll(" ", "_"); +} + +console.log(toUpperSnakeCase("hello there")); +// HELLO_THERE + +console.log(toUpperSnakeCase("lord of the rings")); +// 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..88942684e 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -1,6 +1,62 @@ // In Sprint-1, there is a program written in interpret/to-pounds.js +// ORIGINAL CODE: +//const penceString = "399p"; + +//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"); + +//console.log(`£${pounds}.${pence}`); + + // 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 +// You should call this function a number of times to check it works for different inputs. +// For example: +// toPounds("399p") should return "£3.99" +// toPounds("45p") should return "£0.45" +// toPounds("9p") should return "£0.09" +// toPounds("1200p") should return "£12.00" + +// The current code removes the "p", makes sur ethe number has at least 3 digits, splits pounds and pences and prints it in money format. +// Right now, it only works for "399p". I need it to work for "5p" and "1234p". +// I need to turn it into a function. eg. 'function toPounds(penceString)'. penceString clearly decribes what the input is. + +function toPounds(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(toPounds("399p")); // £3.99 +console.log(toPounds("45p")); // £0.45 +console.log(toPounds("9p")); // £0.09 +console.log(toPounds("1200p")); // £12.00 + diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js index 7c98eb0e8..168c441a9 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -10,25 +10,37 @@ function formatTimeDisplay(seconds) { return `${pad(totalHours)}:${pad(remainingMinutes)}:${pad(remainingSeconds)}`; } +console.log(formatTimeDisplay(61)); +//testing +//console.log(formatTimeDisplay(3661)); // 01:01:01 +//console.log(formatTimeDisplay(45)); // 00:00:45 +//console.log(formatTimeDisplay(3600)); // 01:00:00 + + // 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 +// NOTES: +// This code converst seconds into HH:MM:SS and it uses pad() to make sure every number has 2 digits. e.g. 1 = "01". 0 = "00". +// + + // Questions // a) When formatTimeDisplay is called how many times will pad be called? -// =============> write your answer here +// pad will be called 3 times. pad(totalHours), pad(remainingMinutes) and pad(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 +// num = 0 // c) What is the return value of pad is called for the first time? -// =============> write your answer here +// Return value = 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 +// num = 1 because 61 seconds has 1 second remaining after removing 1 minute (60 seconds). // 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" because 1 is padded to 2 digits. diff --git a/Sprint-2/5-stretch-extend/format-time.js b/Sprint-2/5-stretch-extend/format-time.js index 32a32e66b..87d2a525b 100644 --- a/Sprint-2/5-stretch-extend/format-time.js +++ b/Sprint-2/5-stretch-extend/format-time.js @@ -2,24 +2,56 @@ // 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}` +//); + +// Bug 1: Minutes are hardcoded for PM. It always uses :00 for PM. If the input is "23:45", the output becomes "11:00 pm". +// Bug 2: AM hours are notconverted to 12 hour format. It works for "8:00" but "00:30" becomes "00:30" when it should be "12:30 am". +// Bug 3: 12PM and 12AM are not handled correctly. "12:00" becomes "12:00 am" whjen it should be "12:00 pm", and "00:00" becomes "00:00 am" when it should be "12:00 am". + function formatAs12HourClock(time) { - const hours = Number(time.slice(0, 2)); - if (hours > 12) { - return `${hours - 12}:00 pm`; + let [hours, minutes] = time.split(":"); + hours = Number(hours); + let period = "am"; + + if (hours === 0) { + hours = 12; // midnight + } else if (hours === 12) { + period = "pm"; // noon + } else if (hours > 12) { + hours -= 12; + period = "pm"; } - return `${time} am`; + + const paddedHours = hours.toString().padStart(2, "0"); + + return `${paddedHours}:${minutes} ${period}`; } -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}` -); +//testing the function with various inputs. +console.log(formatAs12HourClock("08:00")); // 08:00 am +console.log(formatAs12HourClock("23:00")); // 11:00 pm +console.log(formatAs12HourClock("00:30")); // 12:30 am +console.log(formatAs12HourClock("12:15")); // 12:15 pm +console.log(formatAs12HourClock("13:45")); // 01:45 pm +console.log(formatAs12HourClock("11:59")); // 11:59 am +console.log(formatAs12HourClock("12:00")); // 12:00 pm