diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js index 653d6f5a0..18eac0562 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -1,5 +1,7 @@ // Predict and explain first... -// =============> write your prediction here +// =============> // =============> write your prediction here +// I predict the code will throw an error because the variable `str` is being declared twice in the same function scope. + // call the function capitalise with a string input // interpret the error message and figure out why an error is occurring @@ -9,5 +11,17 @@ function capitalise(str) { return str; } -// =============> write your explanation here +// =============> write your explanation here +// The function already receives `str` as a parameter. +// Inside the function, it tries to declare `let str = ...`, +// which causes a conflict because JavaScript does not +// allow redeclaring the same variable name in the same scope using `let`. +// This leads to a `SyntaxError: Identifier 'str' has already been declared`. + + // =============> write your new code here +// =============> write your new code here +function capitalise(str) { + let capitalisedStr = `${str[0].toUpperCase()}${str.slice(1)}`; + return capitalisedStr; +} diff --git a/Sprint-2/1-key-errors/1.js b/Sprint-2/1-key-errors/1.js index f2d56151f..2301135b7 100644 --- a/Sprint-2/1-key-errors/1.js +++ b/Sprint-2/1-key-errors/1.js @@ -1,4 +1,9 @@ // Predict and explain first... +// =============> write your prediction here +// I predict this program will throw a `SyntaxError` because +// the parameter `decimalNumber` is being redeclared inside the function using `const`. +// Also, the variable `decimalNumber` is being accessed outside the function where it's not defined. + // Why will an error occur when this program runs? // =============> write your prediction here @@ -15,6 +20,20 @@ function convertToPercentage(decimalNumber) { console.log(decimalNumber); // =============> write your explanation here +// The function already has a parameter named `decimalNumber`, +// but inside the function, it's trying to declare another +// constant with the same name: `const decimalNumber = 0.5;`. +// JavaScript doesn’t allow redeclaring a variable that already exists in the same scope. +// Also, `console.log(decimalNumber)` is outside the function and `decimalNumber` is not +// defined in the global scope, so that will cause a `ReferenceError`. + // 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)); diff --git a/Sprint-2/1-key-errors/2.js b/Sprint-2/1-key-errors/2.js index aad57f7cf..6bb68b409 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -2,19 +2,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 +// The code will throw a **SyntaxError** because you cannot +// use a number (`3`) as a function parameter name. // =============> write your prediction of the error here +// SyntaxError: Unexpected number function square(3) { return num * num; } // =============> write the error message here +// SyntaxError: Unexpected number // =============> explain this error message here +// In JavaScript, function parameters must be valid variable names (identifiers). +// Using a number like `3` directly as a parameter name is invalid syntax, +// so JavaScript throws a `SyntaxError: Unexpected number`. // Finally, correct the code to fix the problem // =============> write your new code here +function square(num) { + return num * num; +} + +console.log(square(3)); + diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js index b27511b41..7ad604f02 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -1,6 +1,10 @@ // Predict and explain first... // =============> write your prediction here +// I predict that the console will log `320` first (from inside the function), +// but then the message will say: "The result of multiplying 10 and 32 is undefined". + +// Explanation: function multiply(a, b) { console.log(a * b); @@ -9,6 +13,16 @@ function multiply(a, b) { console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); // =============> write your explanation here +// The function `multiply` logs the result of `a * b`, but does not return it. +// When it's used inside a template literal, JavaScript evaluates `multiply(10, 32)` as `undefined`, +// because the function has no return value. That's why we get: +// `The result of multiplying 10 and 32 is undefined` — even though `320` is logged separately. // 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..efd11aa12 100644 --- a/Sprint-2/2-mandatory-debug/1.js +++ b/Sprint-2/2-mandatory-debug/1.js @@ -1,13 +1,27 @@ // Predict and explain first... -// =============> write your prediction here +// =============> write your prediction here +// I predict that this will print: "The sum of 10 and 32 is undefined" +// because the function has a return statement with no value. + +// Explanation: function sum(a, b) { return; a + b; + // =============> write your explanation here + // The `return;` statement ends the function early, so `a + b` is never reached. + // In JavaScript, any code after a bare `return;` is ignored (unreachable code). + // That's why the function returns `undefined`, not the actual sum. } console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); -// =============> 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)}`); +// Now the function returns the correct result: 42 + diff --git a/Sprint-2/2-mandatory-debug/2.js b/Sprint-2/2-mandatory-debug/2.js index 57d3f5dc3..da217a8a5 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -2,7 +2,11 @@ // Predict the output of the following code: // =============> Write your prediction here +// I predict that all three log statements will output: "The last digit of 42 is 3", "105 is 3", "806 is 3" +// Because the getLastDigit function doesn’t use the input — it always returns the last digit of the constant +// `num = 103`. +// Original Code const num = 103; function getLastDigit() { @@ -15,10 +19,25 @@ 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 actual 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 function `getLastDigit` doesn't take any parameter, and it always uses the fixed variable `num = 103`. +// So regardless of the input in the log statements, the function 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)}`); // 2 +console.log(`The last digit of 105 is ${getLastDigit(105)}`); // 5 +console.log(`The last digit of 806 is ${getLastDigit(806)}`); // 6 + +// Now the function works correctly by taking a number as input and returning its last digit. -// 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..f7a8d0d55 100644 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -1,19 +1,13 @@ -// 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. +function calculateBMI(weight, height) { + // Square the height (height in meters) + const heightSquared = height * height; -// You will need to implement a function that calculates the BMI of someone based off their weight and height + // Divide weight by height squared to get BMI + const bmi = weight / heightSquared; -// 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 + // Return the BMI rounded to 1 decimal place + return bmi.toFixed(1); // toFixed returns a string, which is fine unless you need it as a number +} -function calculateBMI(weight, height) { - // return the BMI of someone based off their weight and height -} \ No newline at end of file +// Example usage: +console.log(calculateBMI(70, 1.73)); // Output: "23.4" diff --git a/Sprint-2/3-mandatory-implement/2-cases.js b/Sprint-2/3-mandatory-implement/2-cases.js index 5b0ef77ad..51ac5b029 100644 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -1,16 +1,15 @@ -// A set of words can be grouped together in different cases. +// This function converts any sentence into UPPER_SNAKE_CASE +function toUpperSnakeCase(input) { + // Step 1: Convert the string to uppercase + const upperCase = input.toUpperCase(); -// For example, "hello there" in snake case would be written "hello_there" -// UPPER_SNAKE_CASE means taking a string and writing it in all caps with underscores instead of spaces. + // Step 2: Replace all spaces with underscores + const snakeCase = upperCase.replace(/ /g, "_"); -// Implement a function that: + // Step 3: Return the result + return snakeCase; +} -// 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" - -// 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 -// 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 +// Example usage: +console.log(toUpperSnakeCase("hello there")); // Output: "HELLO_THERE" +console.log(toUpperSnakeCase("lord of the rings")); // Output: "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..d75d4291d 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -1,6 +1,22 @@ -// In Sprint-1, there is a program written in interpret/to-pounds.js +function toPounds(penceString) { + const penceStringWithoutTrailingP = penceString.substring(0, penceString.length - 1); + const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); -// 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. + const pounds = paddedPenceNumberString.substring( + 0, + paddedPenceNumberString.length - 2 + ); -// You should call this function a number of times to check it works for different inputs + const pence = paddedPenceNumberString + .substring(paddedPenceNumberString.length - 2) + .padEnd(2, "0"); + + return `£${pounds}.${pence}`; +} + +// Test calls +console.log(toPounds("399p")); // Output: £3.99 +console.log(toPounds("5p")); // Output: £0.05 +console.log(toPounds("45p")); // Output: £0.45 +console.log(toPounds("999p")); // Output: £9.99 +console.log(toPounds("2p")); // Output: £0.02 diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js index 7c98eb0e8..4db69649c 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -17,18 +17,22 @@ function formatTimeDisplay(seconds) { // Questions // a) When formatTimeDisplay is called how many times will pad be called? -// =============> write your answer here +// ===> 3 times — once for hours, once for minutes, and once for seconds. // 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 +// ===> 0 — the first pad call is for totalHours, which is 0 when input is 61 -// 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" — because pad(0) returns the string "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 +// ===> 1 — the last pad call is for remainingSeconds, which is 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 +// ===> "01" — because pad(1) turns 1 into "01" using padStart(2, "0") + +// Example run: +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..219dd8237 100644 --- a/Sprint-2/5-stretch-extend/format-time.js +++ b/Sprint-2/5-stretch-extend/format-time.js @@ -1,25 +1,46 @@ -// This is the latest solution to the problem from the prep. -// 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`; + const minutes = time.slice(3, 5); + + let rawHour; + let period; + + if (hours === 0) { + rawHour = 12; + period = "am"; + } else if (hours === 12) { + rawHour = 12; + period = "pm"; + } else if (hours > 12) { + rawHour = hours - 12; + period = "pm"; + } else { + rawHour = hours; + period = "am"; } - return `${time} am`; + + const formattedHour = String(rawHour).padStart(2, "0"); + + return `${formattedHour}:${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}` -); + +// Tests: +const tests = [ + { input: "00:00", expected: "12:00 am" }, + { input: "08:00", expected: "08:00 am" }, + { input: "12:00", expected: "12:00 pm" }, + { input: "15:30", expected: "03:30 pm" }, + { input: "23:59", expected: "11:59 pm" }, + { input: "11:15", expected: "11:15 am" }, +]; + +tests.forEach(({ input, expected }) => { + const output = formatAs12HourClock(input); + console.assert( + output === expected, + `FAIL: input=${input}, output=${output}, expected=${expected}` + ); +}); + +