diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js index 653d6f5a0..f820cd787 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -1,5 +1,6 @@ // Predict and explain first... // =============> write your prediction here +// The variable str is being declared twice within the same scope, which will cause a syntax error. // call the function capitalise with a string input // interpret the error message and figure out why an error is occurring @@ -8,6 +9,17 @@ function capitalise(str) { let str = `${str[0].toUpperCase()}${str.slice(1)}`; return str; } +const result = capitalise('hello'); +console.log(result); +// SyntaxError: Identifier 'str' has already been declared // =============> write your explanation here +// // The first declaration is in the function parameter and the second one is inside the function body. +// In JavaScript, you cannot declare the same variable name in the same scope using let or const. +// To fix this, we can either rename the inner variable or assign the capitalised value to the parameter itself without redeclaring it. + // =============> write your new code here +function capitalise(str) { + str = `${str[0].toUpperCase()}${str.slice(1)}`; + return str; +} \ 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..155b52d2e 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 +// constant decimalNumber is being declared twice within the same scope, which will cause a syntax error. // 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 +// SyntaxError: Identifier 'decimalNumber' has already been declared +// decimalNumber is declared as a parameter of the function and then again inside the function using const. +// In JavaScript, you cannot declare the same variable name in the same scope using let or const. +// Function input is ignored if a variable with the same name is declared inside the function body. +// const decimalNumber = 0.5 will always output 50% regardless of the input value. // 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.75)); // Example call to test the function \ 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..e96750a29 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -3,18 +3,26 @@ // this function should square any number but instead we're going to get an error -// =============> write your prediction of the error here +// The function does not define the parameter correctly +// Instead, the input has been inserted where the parameter name should be +// Then num is being used in the function body but it is not defined anywhere -function square(3) { - return num * num; -} - -// =============> write the error message here +// function square(3) { + // return num * num; +// } -// =============> explain this error message here +// SyntaxError: Unexpected number +// The number 3 is used directly in the function parameter +// The function parameter should be num to accept any number as input +// Then the function body can use num to square the input value +//Defining a function should describe the parameters it expects, not specific values // Finally, correct the code to fix the problem - -// =============> write your new code here +function square(num) { + return num * num; +} +console.log(square(5)); +console.log(square(10)); +console.log(square(-3)); diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js index b27511b41..f60739987 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -1,6 +1,7 @@ // Predict and explain first... -// =============> write your prediction here +// console.log is being used inside the multiply function, which does not return any value. +// This will result in undefined being printed in the template literal. function multiply(a, b) { console.log(a * b); @@ -8,7 +9,15 @@ function multiply(a, b) { console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); -// =============> write your explanation here +// Output in the terminal was: "320 +// The result of multiplying 10 and 32 is undefined" +// Console.log within the function prints the product of the calculation, but the function does not return the value to the global scope. +// Therefore within the template literal, the meaning of the multiply function call is undefined // 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)}`); diff --git a/Sprint-2/2-mandatory-debug/1.js b/Sprint-2/2-mandatory-debug/1.js index 37cedfbcf..001d527b0 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 +// a + b should be written on the same line as return statement +// This function will not return anything because of the semicolon, so when the function is call on line 10 it will be undefined. function sum(a, b) { return; @@ -8,6 +9,11 @@ function sum(a, b) { console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); -// =============> write your explanation here +// Terminal output "The sum of 10 and 32 is undefined" +// Console.log is calling a function that was not defined because the function body has an incorrect return statement. + // 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..6ed853c62 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -1,7 +1,8 @@ // Predict and explain first... // Predict the output of the following code: -// =============> Write your prediction here +// This function will always return the last digit of the number 103. +// This is because the variable num is hardcoded to 103 within the function scope. const num = 103; @@ -14,11 +15,21 @@ 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 number 103 is assigned as a constant variable so the function will always use num as 103 +// So when the function is called with different arguments, it still returns the last digit of 103 which is 3 + // 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..5ebbab192 100644 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -1,19 +1,24 @@ // Below are the steps for how BMI is calculated - // The BMI calculation divides an adult's weight in kilograms (kg) by their height in metres (m) squared. - // For example, if you weigh 70kg (around 11 stone) and are 1.73m (around 5 feet 8 inches) tall, you work out your BMI by: - // squaring your height: 1.73 x 1.73 = 2.99 // dividing 70 by 2.99 = 23.41 // Your result will be displayed to 1 decimal place, for example 23.4. - // You will need to implement a function that calculates the BMI of someone based off their weight and height - // Given someone's weight in kg and height in metres // 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) { - // return the BMI of someone based off their weight and height -} \ No newline at end of file + let bmi = (weight / (height * height)); + return Number(bmi.toFixed(1)); +} +console.log(calculateBMI(70, 1.73)); +console.log(calculateBMI(95, 1.82)); +console.log(calculateBMI(52, 1.6)); +console.log(calculateBMI(110, 1.75)); +console.log(calculateBMI(65, 1.9)); + +console.assert(typeof calculateBMI(60, 1.65) === 'number', 'Should return a number'); +console.assert(calculateBMI(60, 1.65) === 22.0, 'Should correctly calculate BMI'); +console.log('All tests passed!'); \ 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..5408c5708 100644 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -14,3 +14,11 @@ // 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) { + return string.toUpperCase().replace(/ /g, "_"); +} +console.log(toUpperSnakeCase("hello there")); +console.log(toUpperSnakeCase("lord of the rings")); +console.log(toUpperSnakeCase("javascript 4eva")); +console.log(toUpperSnakeCase("unit testing is important!!")); \ No newline at end of file diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js index 6265a1a70..a631616a2 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -1,6 +1,37 @@ // In Sprint-1, there is a program written in interpret/to-pounds.js - // 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) { + penceString = String(penceString); // ensures input is treated as a string even if number is inputted + // const penceStringWithoutTrailingP = penceString.substring( + let penceStringWithoutTrailingP = penceString; + if (penceString.endsWith("p")) { + penceStringWithoutTrailingP = penceString.substring( + 0, + penceString.length - 1 + ); + } // This prevents the last characters from being sliced off if there is no p. + + 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("481p")); +console.log(toPounds("50p")); +console.log(toPounds("5p")); +console.log(toPounds("0p")); +console.log(toPounds("12345p")); +console.log(toPounds("9")); // edge case: missing 'p' at the end, returns 0 rather than error because last character is sliced off +// Can be fixed by changing line 8 +console.log(toPounds("abc")); // Works but returns nonsense value +console.log(toPounds(123)); // Works with number input because of line 7 converting to string diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js index 7c98eb0e8..8afc4a223 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -2,7 +2,7 @@ function pad(num) { return num.toString().padStart(2, "0"); } -function formatTimeDisplay(seconds) { +function formatTimeDisplay(num) { const remainingSeconds = seconds % 60; const totalMinutes = (seconds - remainingSeconds) / 60; const remainingMinutes = totalMinutes % 60; @@ -17,18 +17,23 @@ function formatTimeDisplay(seconds) { // Questions // a) When formatTimeDisplay is called how many times will pad be called? -// =============> write your answer here +// 3 times: the return statement contains 3 pad calls within the formatTimeDisplay function. // 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 as when the input is 61 seconds, remainingSeconds = 1, totalMinutes = 1, remainingMinutes = 1, totalHours = 0. +// totalHours = (totalMinutes - remainingMinutes) / 60 = (1 - 1) / 60 = 0 / 60 = 0 (dividing once into minutes and once into hours). -// c) What is the return value of pad is called for the first time? -// =============> write your answer here +// c) What is the return value of pad when called for the first time? +// "00" as num is 0, and padStart(2, "0") adds a leading zero to make it 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 last time pad is called, num is assigned the value of remainingSeconds, which is 1. +// Go to line const remainingSeconds = seconds % 60; and use input of seconds = 61 to calculate remainder of 61/60 = 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 last time pad is called, it uses remainingSeconds which is 1 +// The call is pad(1) which converts to a string and adds a leading 0 if there's less than 2 characters +// So, the return value is "01". +// The final formatted time string for an input of 61 seconds is "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..04c219987 100644 --- a/Sprint-2/5-stretch-extend/format-time.js +++ b/Sprint-2/5-stretch-extend/format-time.js @@ -3,10 +3,18 @@ // 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) { + if (!/^\d{2}:\d{2}$/.test(time)) { //If input does not match HH:MM format, returns string "Invalid time format" + return "Invalid time format"; +} + const hours = Number(time.slice(0, 2)); - if (hours > 12) { - return `${hours - 12}:00 pm`; - } + const minutes = time.slice(-2); + + if (hours === 0) return `12:${minutes} am`; + if (hours === 12) return `12:${minutes} pm`; + if (hours === 24) return `12:${minutes} am`; + if (hours > 12) return `${hours - 12}:${minutes} pm`; + return `${time} am`; } @@ -23,3 +31,10 @@ console.assert( currentOutput2 === targetOutput2, `current output: ${currentOutput2}, target output: ${targetOutput2}` ); + +console.log(formatAs12HourClock("12:00")); // +console.log(formatAs12HourClock("00:00")); // +console.log(formatAs12HourClock("15:30")); // +console.log(formatAs12HourClock("11:45")); // +console.log(formatAs12HourClock("24:00")); // +console.log(formatAs12HourClock("ab:cd")); //