diff --git a/Sprint-1/1-key-exercises/3-paths.js b/Sprint-1/1-key-exercises/3-paths.js index ab90ebb28..944a4edc6 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -10,14 +10,20 @@ // (All spaces in the "" line should be ignored. They are purely for formatting.) const filePath = "/Users/mitch/cyf/Module-JS1/week-1/interpret/file.txt"; + const lastSlashIndex = filePath.lastIndexOf("/"); const base = filePath.slice(lastSlashIndex + 1); console.log(`The base part of ${filePath} is ${base}`); +const dir = filePath.slice(0, lastSlashIndex); +const lastDotIndex = base.lastIndexOf("."); +const ext = base.slice(lastDotIndex + 1); + +console.log(`The directory part is: ${dir}`); +console.log(`The file extension is: ${ext}`); + // Create a variable to store the dir part of the filePath variable // Create a variable to store the ext part of the variable -const dir = ; -const ext = ; // https://www.google.com/search?q=slice+mdn \ No newline at end of file diff --git a/Sprint-1/3-mandatory-interpret/1-percentage-change.js b/Sprint-1/3-mandatory-interpret/1-percentage-change.js index e24ecb8e1..3640d9b2f 100644 --- a/Sprint-1/3-mandatory-interpret/1-percentage-change.js +++ b/Sprint-1/3-mandatory-interpret/1-percentage-change.js @@ -9,6 +9,19 @@ const percentageChange = (priceDifference / carPrice) * 100; console.log(`The percentage change is ${percentageChange}`); +// carPrice = Number(carPrice.replaceAll(",", "")); +// priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); +// const percentageChange = (priceDifference / carPrice) * 100; + +// There is no function being called in this line above. +// This is just a mathematical expression that divides +// priceDifference by carPrice, then multiplies by 100 to get a percentage. +// Because a function call in JavaScript is something that looks like, +// functionName(...) +// But in this (priceDifference / carPrice) * 100, there are no parentheses +// after a function name or no function names being used here. +// So this line does not contain a function call. + // Read the code and then answer the questions below // a) How many function calls are there in this file? Write down all the lines where a function call is made diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js index 653d6f5a0..a4e48cf28 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -1,7 +1,10 @@ // Predict and explain first... // =============> write your prediction here - +// - The code will throw a SyntaxError due to variable redeclaration. // call the function capitalise with a string input +// - The function provided contains a syntax error because it attempts to redeclare +// - the parameter str within the function using let, which is not permitted +// - in JavaScript. Below is the corrected version of the function, followed by an example of how it can be called. // interpret the error message and figure out why an error is occurring function capitalise(str) { @@ -10,4 +13,22 @@ function capitalise(str) { } // =============> write your explanation here +// - When code run, this "SyntaxError: Identifier 'str' has +// - already been declared" will show +// - In the function capitalise(str), the parameter str is already declared. +// - But inside the function, you're trying to declare a new variable +// - with the same name using let str = .... +// - JavaScript doesn't allow declaring a new variable with the +// same name as a function parameter using let or const within the same scope. // =============> write your new code here +function capitalise(str) { + str = `${str[0].toUpperCase()}${str.slice(1)}`; + return str; + +} + + capitalise(hello); + console.log(capitalise('hello')); + // I used "hello" as an example input when + // calling the capitalise function: + // Output: 'Hello' \ 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..bc6d2bd20 100644 --- a/Sprint-2/1-key-errors/1.js +++ b/Sprint-2/1-key-errors/1.js @@ -1,7 +1,25 @@ // Predict and explain first... + + + + // Why will an error occur when this program runs? +// +// - // =============> write your prediction here +// - Goal: This function is meant to take a decimal (like 0.5) +// - and return it as a percentage (like "50%"). +// expected use: +convertToPercentage(0.5); +// - should return "50" +// - What we expect: +// - Input: 0.5 +// - Multiply by 100: 0.5 * 100 = 50 +// - Convert to string with %: "50%" +// - Return "50%" + + // Try playing computer with the example to work out what is going on @@ -14,7 +32,31 @@ function convertToPercentage(decimalNumber) { console.log(decimalNumber); +Play computer: +function convertToPercentage(decimalNumber){ + const decimalNumber = 0.5; // Error! 'decimalNumber' already declared + const percentage = `${decimalNumber * 100}%`; + return percentage; + +} +// - The moment the engine sees const decimalNumber = 0.5;, it throws an error +// - because decimalNumber was already defined as a parameter. +// - So, the function never runs past that point. + // =============> write your explanation here +// - - SyntaxError: Identifier 'decimalNumber' has already been declared +// - This is because of this... +// - The variable decimalNumber is declared twice: +// - First, as a parameter in the function declaration: +// - function convertToPercentage(decimalNumber) +// - Then again, inside the function body: +// - const decimalNumber = 0.5; +// - JavaScript does not allow a const to be re-declared using +// - the same name as a parameter within the same function scope. This results in a syntax error. // Finally, correct the code to fix the problem // =============> write your new code here +function convertToPercentage(decimalNumber) { + const percentage = `${decimalNumber * 100}%`; + return percentage; +} diff --git a/Sprint-2/1-key-errors/2.js b/Sprint-2/1-key-errors/2.js index aad57f7cf..769a5536a 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -4,17 +4,48 @@ // this function should square any number but instead we're going to get an error // =============> write your prediction of the error here +// - This function is intended to square any number passed to it — meaning, +// - if you pass in 3, it should return 9. +// - However, the code as written will produce a syntax and reference error for two reasons: +// - 3 is not a valid parameter name — parameter names must be identifiers (like num, x, etc.). +// - The variable num is used but never declared inside the function. +// - Prediction of the Error +// - We expect two issues: +// - JavaScript will throw a syntax error because 3 +// is not a valid parameter name. +// - If the syntax were somehow ignored, the code would +// later throw a ReferenceError because num is undefined. + function square(3) { return num * num; } // =============> write the error message here +// - The first (and stopping) error would be: +// - SyntaxError: Unexpected number +// - If one fixed the syntax but left num undeclared, one'd see: +// - ReferenceError: num is not defined // =============> explain this error message here +// - SyntaxError: Unexpected number +// - This means JavaScript found a number (3) where it +// - expected a variable name — numbers can't be used as parameter names. +// - ReferenceError: num is not defined +// - This happens when the code tries to use a +// - variable num that hasn’t been declared or passed in. + // Finally, correct the code to fix the problem // =============> write your new code here +// - We need to use a valid parameter name like num +// - Make sure we use that parameter consistently in the return statement. +function square(num) { + return num * num; +} +// Example usage: +console.log(square(3)); // Output: 9 +console.log(square(5)); // Output: 25 diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js index b27511b41..0abc7164c 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -1,6 +1,12 @@ // Predict and explain first... // =============> write your prediction here +// This answer is similar to the description below. +// - Would expect to print: +// - The result of multiplying 10 and 32 is 320 +// - But based on how the function is written, here's what will actually happen: +// - The result of multiplying 10 and 32 is undefined + function multiply(a, b) { console.log(a * b); @@ -9,6 +15,20 @@ function multiply(a, b) { console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); // =============> write your explanation here +// - The code is trying to multiply the values 10 and 32 and display the result inside a sentence: +console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); +// - However, the function multiply(a, b) only logs the result using +// - console.log(a * b) — it doesn't return the value. +// - Since there’s no return statement, the function returns undefined by default. +// - As a result, the template string ends up displaying: +// - The result of multiplying 10 and 32 is undefined +// - Even though the actual product (320) is printed on a separate line, +// - it’s not included in the sentence. // 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-2/2-mandatory-debug/1.js b/Sprint-2/2-mandatory-debug/1.js index 37cedfbcf..ef8723136 100644 --- a/Sprint-2/2-mandatory-debug/1.js +++ b/Sprint-2/2-mandatory-debug/1.js @@ -1,5 +1,8 @@ // Predict and explain first... // =============> write your prediction here +// - Expecting the code to print 'the sum of 10 and 32 is 42' +// - Because it's calling a function sum(10, 32) and trying to insert the result into a sentence. + function sum(a, b) { return; @@ -9,5 +12,20 @@ function sum(a, b) { console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); // =============> write your explanation here +// - The function includes this: +return; +a + b; +// - In JavaScript, when one write return; on its own line, +// - the function immediately exits and returns undefined. +// - The line a + b; is never run, because the function already returned. +// - This is due to JavaScript's automatic semicolon insertion — it treats return; as a complete statement. +// - The actual Output, the sum of 10 and 32 is undefined + + // 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..d6d380860 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -2,7 +2,7 @@ // Predict the output of the following code: // =============> Write your prediction here - +// - I think this will just keep returning the last digit of 103, no matter what number I pass in. const num = 103; function getLastDigit() { @@ -15,10 +15,48 @@ 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 -// Finally, correct the code to fix the problem +// 1. How the function is defined matters: +// The function getLastDigit() is defined without any +// parameters—its parentheses are empty: + function getLastDigit() { ... } +// 2. No parameters means no inputs: +// Even though one call the function with values like +// getLastDigit(42), getLastDigit(105), or getLastDigit(806), +// these values are ignored because the function +// definition does not accept any arguments. +// 3. Uses the global variable num: +// Inside the function, it only looks at the global variable: + const num = 103; +// So, no matter what one passes in, the function always uses 103. +// 4. Returns last digit of num: +// The function converts num (103) to a string +// and takes the last character: + num.toString().slice(-1) // returns "3" +// 5. Therefore, the output is always "3": +// When you run: +console.log(`The last digit of 42 is ${getLastDigit(42)}`); +// It prints: The last digit of 42 is 3 +// Because the function ignores the 42 and returns the last digit of 103. +// Finally, correct the code to fix the problem // =============> 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)}`); // '2' +console.log(`The last digit of 105 is ${getLastDigit(105)}`); // '5' +console.log(`The last digit of 806 is ${getLastDigit(806)}`); // '6' + +// To make it work the function must be defined with a parameter (like num) inside the +// parentheses so it can accept different numbers when called. This way, the +// function works with any input number instead of always using a fixed global value. + // 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..c60065cec 100644 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -15,5 +15,12 @@ // 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 + const bmi = weight / (height * height); + return parseFloat(bmi.toFixed(1)); + } +console.log(calculateBMI(70, 1.73)); // Output: 23.4 + +// Step-by-step Calculation: +// Height squared = 1.73 × 1.73 = 2.9929 +// BMI = 70 / 2.9929 ≈ 23.38 +// Rounded to 1 decimal place = 23.4 \ 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..33be912f9 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 + +function toUpperSnakeCase(input) { + const upperSnake = input.split(' ').join('_').toUpperCase(); + return upperSnake; + } + + console.log(toUpperSnakeCase("I always enjoy the class at CYF on Saturdays")); + // Expected output: "I_ALWAYS_ENJOY_THE_CLASS_AT_CYF_ON_SATURDAYS + +// This is what I did. +// I wrote a function called toUpperSnakeCase that takes a sentence and turns it into UPPER_SNAKE_CASE. +// Inside the function, I: +// Split the string into words using .split(' ') +// Joined the words with underscores using .join('_') +// Changed all letters to uppercase using .toUpperCase() +// Stored the result in a const variable called upperSnake +// Returned that final result +// Then I tested the function with the sentence: +// "I enjoy the class at CYF on Saturdays", +// and it returned: "I_ENJOY_THE_CLASS_AT_CYF_ON_SATURDAYS" + diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js index 6265a1a70..af1deb419 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -4,3 +4,35 @@ // 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 formatPenceToPounds(amountInPence) { + // Remove the "p" at the end of the string (e.g., "399p" → "399") + const penceStringWithoutTrailingP = amountInPence.substring( + 0, + amountInPence.length - 1 + ); + + // Add leading zeros so it’s at least 3 digits (e.g., "9" → "009") + const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); + + // Get all but the last 2 digits as the pounds part (e.g., "399" → "3") + const pounds = paddedPenceNumberString.substring( + 0, + paddedPenceNumberString.length - 2 + ); + + // Get the last 2 digits as the pence part (e.g., "399" → "99") + const pence = paddedPenceNumberString + .substring(paddedPenceNumberString.length - 2) + .padEnd(2, "0"); + + // Return the formatted result in pounds (e.g., "£3.99") + return `£${pounds}.${pence}`; + } + +// Different inputs: +console.log(toPounds("499p")); // £4.99 +console.log(toPounds("99p")); // £0.99 +console.log(toPounds("7p")); // £0.07 +console.log(toPounds("0p")); // £0.00 +console.log(toPounds("1234p"));// £12.34 diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js index 7c98eb0e8..555acbf3a 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -18,17 +18,31 @@ function formatTimeDisplay(seconds) { // a) When formatTimeDisplay is called how many times will pad be called? // =============> write your answer here +// 3 times, once for hours, minutes and seconds. // Call formatTimeDisplay with an input of 61, now answer the following: +// This happens when formatTimeDisplay(61) is called: +// remainingSeconds = 61 % 60 = 1 +// totalMinutes = (61 - 1) / 60 = 60 / 60 = 1 +// remainingMinutes = 1 % 60 = 1 +// totalHours = (1 - 1) / 60 = 0 / 60 = 0 // b) What is the value assigned to num when pad is called for the first time? // =============> write your answer here +// The answer is 0, because first call is pad(totalHours), and totalHours is 0. // c) What is the return value of pad is called for the first time? // =============> write your answer here +// The answer is "00", because pad(0) → 0.toString() → "0" → "0".padStart(2, "0") → "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 +// The answer is 1. The last call is pad(remainingSeconds). From earlier: remainingSeconds = 1, so num = 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 answer is "01". Pad(1) → 1.toString() → "1" → "1".padStart(2, "0") → "01" + + diff --git a/Sprint-2/5-stretch-extend/format-time.js b/Sprint-2/5-stretch-extend/format-time.js index 32a32e66b..8c0c9b5b1 100644 --- a/Sprint-2/5-stretch-extend/format-time.js +++ b/Sprint-2/5-stretch-extend/format-time.js @@ -2,13 +2,45 @@ // 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. +// My final version of the function that converts 24-hour time to 12-hour format +// It handles midnight (00:00), noon (12:00), and all edge cases correctly + +// function formatAs12HourClock(time) { +// const hours = Number(time.slice(0, 2)); +// if (hours > 12) { +// return `${hours - 12}:00 pm`; +// } +// return `${time} am`; +// } + function formatAs12HourClock(time) { - const hours = Number(time.slice(0, 2)); - if (hours > 12) { - return `${hours - 12}:00 pm`; + const [hourStr, minute] = time.split(":"); + let hours = Number(hourStr); + let period = "am"; + + if (hours === 0) { + hours = 12; // Midnight becomes 12 + } else if (hours === 12) { + period = "pm"; // Noon stays 12 but changes to pm + } else if (hours > 12) { + hours = hours - 12; + period = "pm"; // Any hour after 12 becomes pm + } + // Return the formatted time as 12-hour string with am or pm + return `${hours}:${minute} ${period}`; } - return `${time} am`; -} + + // Test cases to check my function works as expected +console.log(formatAs12HourClock("00:00")); // 12:00 am +console.log(formatAs12HourClock("01:30")); // 1:30 am +console.log(formatAs12HourClock("12:00")); // 12:00 pm +console.log(formatAs12HourClock("15:45")); // 3:45 pm +console.log(formatAs12HourClock("23:59")); // 11:59 pm + +// I have tested edge cases like midnight (00:00) and noon (12:00) +// and also tested hours before and after noon. +// I understand the use of if conditions, string splitting, and formatting return values. + const currentOutput = formatAs12HourClock("08:00"); const targetOutput = "08:00 am";