From 6e9aa77897fe79f6b19a144bcc380c8383bb675d Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Tue, 24 Jun 2025 22:37:11 +0100 Subject: [PATCH 01/32] update: Fix variable redeclaration error in capitalise function and update comments for clarity Sprint-2/1-key-errors/0.js --- Sprint-2/1-key-errors/0.js | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js index 653d6f5a0..36cdb5dc3 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -4,10 +4,25 @@ // 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; +// } // =============> write your explanation here +// The function capitalize is trying to take a string input and return it with the first letter capitalized. +// However, the error occurs because the variable 'str' is being declared twice: once as a parameter and again inside the function. +// This is not allowed in JavaScript, as 'let' does not allow redeclaration of the same variable in the same scope. +// This causes a syntax error because you cannot redeclare a variable with 'let' in the same scope. // =============> write your new code here + +function capitalise(str) { + let name = `${str[0].toUpperCase()}${str.slice(1)}`; + return name; +} +capitalise("hello, check "); +console.log(capitalise("hello, check ")); +// =============> write your explanation here +// The function now uses a different variable name 'name' instead of 'str' inside the function. +// This avoids the redeclaration error. The function takes a string input, capitalizes the first letter, and returns the modified string. +// However, the return statement still returns 'str' instead of 'name', which is a mistake. From 230213096caba385cbdfc00cc41c983ba7362016 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Tue, 24 Jun 2025 22:47:57 +0100 Subject: [PATCH 02/32] update: convertToPercentage function to fix redeclaration error and explain Sprint-2/1-key-errors/1.js --- Sprint-2/1-key-errors/1.js | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/Sprint-2/1-key-errors/1.js b/Sprint-2/1-key-errors/1.js index f2d56151f..723a872f1 100644 --- a/Sprint-2/1-key-errors/1.js +++ b/Sprint-2/1-key-errors/1.js @@ -5,16 +5,35 @@ // Try playing computer with the example to work out what is going on -function convertToPercentage(decimalNumber) { - const decimalNumber = 0.5; - const percentage = `${decimalNumber * 100}%`; - - return percentage; -} +// function convertToPercentage(decimalNumber) { +// const decimalNumber = 0.5; +// The above line will cause an error because 'decimalNumber' is being redeclared with 'const' +// after it has already been defined as a parameter of the function. +// This will result in a SyntaxError: Identifier 'decimalNumber' has already been declared. +// it is trying to declare a new constant variable with the same name as the parameter of the function: decimalNumber +// const percentage = `${decimalNumber * 100}%`; +// The above line correctly converts the decimal number to a percentage by multiplying it by 100 +// and appending a '%' sign. +// However, the function will not execute due to the redeclaration error. -console.log(decimalNumber); +// return percentage; +// // } +// console.log(decimalNumber); +// console.log(decimalNumber) outside the function — but decimalNumber was only defined inside the function. // =============> write your explanation here // Finally, correct the code to fix the problem // =============> write your new code here +function convertToPercentage(decimalNumber) { + const percentage = `${decimalNumber * 100}%`; + return percentage; +} +// =============> write your explanation here +// The function now correctly takes a decimal number as input, converts it to a percentage by multiplying it by 100, +// and returns the result as a string with a '%' sign appended. The redeclaration error has been fixed by removing the +// unnecessary declaration of 'decimalNumber' inside the function. The function can now be called with a decimal number, +// and it will return the corresponding percentage string. +console.log(convertToPercentage(0.5)); // "50%" + +// The function now works correctly and returns the expected output without any errors. From 1b1b8c930bef2b91b79c03597d40799cb7fffced Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Tue, 24 Jun 2025 22:49:46 +0100 Subject: [PATCH 03/32] update: Predict and explain code, then fix square function to correct parameter definition and error explanation in Sprint-2/1-key-errors/2.js --- Sprint-2/1-key-errors/2.js | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/Sprint-2/1-key-errors/2.js b/Sprint-2/1-key-errors/2.js index aad57f7cf..84ec2dad9 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -1,20 +1,26 @@ - // Predict and explain first BEFORE you run any code... - +// the will be an error // this function should square any number but instead we're going to get an error +// Why will an error occur when this program runs? +//because the function parameter is incorrectly defined by real number instead of a variable name + // =============> 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 // =============> explain this error message here - +// The error occurs because the function parameter is defined as a number (3) instead of a variable name. +// In JavaScript, function parameters must be variable names, not literal values. JavaScript is expecting a parameter name in the parentheses, not a value. // Finally, correct the code to fix the problem // =============> write your new code here - +function square(num) { + return num * num; +} +console.log(square(3)); // This will not work because 'num' is not defined outside the function From 58aa84012e6600a2ecd03f5e6b8f41b59286b224 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Tue, 24 Jun 2025 22:52:06 +0100 Subject: [PATCH 04/32] update: Fix multiply function to return the product of two numbers and explain function for clarity in Sprint-2/2-mandatory-debug/0.js --- Sprint-2/2-mandatory-debug/0.js | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js index b27511b41..2b688059e 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -1,14 +1,30 @@ // Predict and explain first... +// The code below is intended to multiply two numbers and log the result. +// However, it currently does not return the result correctly. +// The function `multiply` is defined to take two parameters `a` and `b`. +// It logs the product of `a` and `b` but does not return it. +// The console.log statement outside the function attempts to log the result of calling `multiply(10, 32)`. +// The expected output is "The result of multiplying 10 and 32 is 320". +// However, since `multiply` does not return a value, the output will be "The result of multiplying 10 and 32 is undefined". // =============> write your prediction here function multiply(a, b) { - console.log(a * b); + // This function multiplies two numbers and logs the result + // but does not return it. + // It should return the product instead of just logging it. + // The current implementation will not return the product. + //console.log(a * b); + // This line should be changed to return the product + return a * b; // Corrected to return the product } console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); - // =============> write your explanation here +// // The code is intended to multiply two numbers and log the result. +// However, it currently does not return the result correctly. +// The expected output is "The result of multiplying 10 and 32 is 320". +// The current output will be "The result of multiplying 10 and 32 is undefined". // Finally, correct the code to fix the problem // =============> write your new code here From 6bc6fa9b2642e7045c914e75e98d91de39e99e0d Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Tue, 24 Jun 2025 22:54:00 +0100 Subject: [PATCH 05/32] update: Predict and explain the output, Fix sum function to correctly return the sum of two numbers and explain code for clarity in Sprint-2/2-mandatory-debug/1.js --- Sprint-2/2-mandatory-debug/1.js | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/Sprint-2/2-mandatory-debug/1.js b/Sprint-2/2-mandatory-debug/1.js index 37cedfbcf..06e6c7e84 100644 --- a/Sprint-2/2-mandatory-debug/1.js +++ b/Sprint-2/2-mandatory-debug/1.js @@ -1,13 +1,20 @@ // Predict and explain first... // =============> write your prediction here +// The sum of 10 and 32 is 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 +// The function called `sum` is defined to take two parameters `a` and `b`, but it does not return the result of adding them together. +// Instead, it has a `return` statement which exits the function without returning any value. // Finally, correct the code to fix the problem // =============> write your new code here +function sum(a, b) { + return a + b; +} +console.log(sum(10, 32)); From 889a9a97dff240db95727406615ed78086a4450f Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Tue, 24 Jun 2025 22:58:14 +0100 Subject: [PATCH 06/32] update: predict the output, explain the cause of the problem, then Fix getLastDigit function to correctly return the last digit of a number and update comments for clarity in Sprint-2/2-mandatory-debug/2.js --- Sprint-2/2-mandatory-debug/2.js | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/Sprint-2/2-mandatory-debug/2.js b/Sprint-2/2-mandatory-debug/2.js index 57d3f5dc3..c98b6b869 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -1,24 +1,36 @@ // Predict and explain first... +// This code is intended to find the last digit of a number, but it has a bug. // Predict the output of the following code: +// Predict the output of the following code is '3' for the input 103. since the last digit of 103 is 3 and it is a global variable, so regardless of the input, it will always return the last digit of the global variable `num` which is 103. // =============> Write your prediction here -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 +// The last digit of 42 is 3 +// The last digit of 105 is 3 +// The last digit of 806 is 3 + // =============> write the output here // Explain why the output is the way it is // =============> write your explanation here +// The output is always '3' because the function `getLastDigit` is using a global variable `num` which is set to 103 // 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 From 5d354cd87918658fe02960edd9b24b15a06e029b Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Tue, 24 Jun 2025 23:03:12 +0100 Subject: [PATCH 07/32] update: Add output explanation for getLastDigit function to clarify why it always returns '3' in Sprint-2/2-mandatory-debug/2.js --- Sprint-2/2-mandatory-debug/2.js | 1 + 1 file changed, 1 insertion(+) diff --git a/Sprint-2/2-mandatory-debug/2.js b/Sprint-2/2-mandatory-debug/2.js index c98b6b869..f3d78fc1e 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -21,6 +21,7 @@ // The last digit of 806 is 3 // =============> write the output here +// The output is always '3' // Explain why the output is the way it is // =============> write your explanation here // The output is always '3' because the function `getLastDigit` is using a global variable `num` which is set to 103 From 3c47903b0c1aca8deda86bfe5da15e5edf798cb4 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Tue, 24 Jun 2025 23:04:59 +0100 Subject: [PATCH 08/32] update: Implement calculateBMI function to compute Body Mass Index based on weight and height, including detailed comments for clarity in Sprint-2/3-mandatory-implement/1-bmi.js --- Sprint-2/3-mandatory-implement/1-bmi.js | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/Sprint-2/3-mandatory-implement/1-bmi.js b/Sprint-2/3-mandatory-implement/1-bmi.js index 17b1cbde1..c25c70eb4 100644 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -15,5 +15,15 @@ // 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 + // return the BMI of someone based off their weight and height + // calculate the height squared + const heightSquared = height * height; + // calculate the BMI + const BMI = weight / heightSquared; + // return the BMI to 1 decimal place + return BMI.toFixed(1); +} +let weight = 70; // in kg +let height = 1.73; // in meters + +console.log(`BMI is ${calculateBMI(weight, height)}`); From 32c94e5bda0aea254b051a4871f09af834f5782c Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Tue, 24 Jun 2025 23:06:16 +0100 Subject: [PATCH 09/32] update: Add toUpperSnakeCase function to convert strings to UPPER_SNAKE_CASE with example usage Sprint-2/3-mandatory-implement/2-cases.js --- Sprint-2/3-mandatory-implement/2-cases.js | 33 +++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/Sprint-2/3-mandatory-implement/2-cases.js b/Sprint-2/3-mandatory-implement/2-cases.js index 5b0ef77ad..a3e5f37f9 100644 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -14,3 +14,36 @@ // 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) { + //split the string into an array of words + const wordsArray = string.split(" "); + // Convert each word to uppercase + const upperWordsArray = wordsArray.map((word) => word.toUpperCase()); + // Join the array back into a string with underscores + const toUpperSnakeCase = upperWordsArray.join("_"); + // Return the string in UPPER_SNAKE_CASE + return toUpperSnakeCase; +} +// Example usage for this function +// let string = "hello there"; + +// console.log(`The string in UPPER_SNAKE_CASE is: ${toUpperSnakeCase(string)}`); + +console.log( + `The string in UPPER_SNAKE_CASE for 'hello there' is: ${toUpperSnakeCase( + "hello there" + )}` +); + +console.log( + `The string in UPPER_SNAKE_CASE for 'lord of the rings' is: ${toUpperSnakeCase( + "lord of the rings" + )}` +); + +console.log( + `The string in UPPER_SNAKE_CASE for 'example usage for this function' is: ${toUpperSnakeCase( + "example usage for this function" + )}` +); From 1c4a2db3b5598f1b9587fab7de17b6577dfd0d91 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Tue, 24 Jun 2025 23:07:28 +0100 Subject: [PATCH 10/32] update: Implement toPounds function to convert pence strings to formatted pounds with example usage Sprint-2/3-mandatory-implement/3-to-pounds.js --- Sprint-2/3-mandatory-implement/3-to-pounds.js | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js index 6265a1a70..7f3ee9d2e 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -4,3 +4,32 @@ // 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) { + // Remove the trailing "p" from the string + const penceStringWithoutTrailingP = penceString.substring( + 0, + penceString.length - 1 + ); + + // Ensure the number has at least 3 digits by padding from the left with zeros + const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); + + // Extract the pound portion + const pounds = paddedPenceNumberString.substring( + 0, + paddedPenceNumberString.length - 2 + ); + + // Extract the pence portion and pad right if needed + const pence = paddedPenceNumberString + .substring(paddedPenceNumberString.length - 2) + .padEnd(2, "0"); + + // Return the formatted result + return `£${pounds}.${pence}`; +} + +// Example usage: +console.log(toPounds("399p")); +console.log(toPounds("155p")); +console.log(toPounds("75p")); From a349242441ce121e559261f747a9ec1d0ea076d9 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Tue, 24 Jun 2025 23:11:44 +0100 Subject: [PATCH 11/32] fix: Understanding and explain the behavior of formatTimeDisplay() and pad() in sprint -2/ time-format.js --- Sprint-2/4-mandatory-interpret/time-format.js | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js index 7c98eb0e8..1dcb19c4b 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -11,7 +11,7 @@ function formatTimeDisplay(seconds) { return `${pad(totalHours)}:${pad(remainingMinutes)}:${pad(remainingSeconds)}`; } -// You will need to play computer with this example - use the Python Visualiser https://pythontutor.com/visualize.html#mode=edit +// You will need to play computer with this example - use the Python Visualizer https://pythontutor.com/visualize.html#mode=edit // to help you answer these questions // Questions @@ -20,15 +20,18 @@ function formatTimeDisplay(seconds) { // =============> write your answer here // Call formatTimeDisplay with an input of 61, now answer the following: - +// 3 times which is once each for hours, minutes, and seconds. // b) What is the value assigned to num when pad is called for the first time? // =============> write your answer here - +// 0, because pad is first called with totalHours, which is 0. // c) What is the return value of pad is called for the first time? // =============> write your answer here - +// '00' pad(0) becomes "0" → padded to "00" using padStart(2, "0"). // 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, because the last call to pad is with remainingSeconds, which is 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", pad(1) becomes "1" → padded to "01" using padStart(2, "0"). + +// the final output of formatTimeDisplay(61) will be "00:01:01". From 0d71e05e75b45f03e7b3c11f344811c992c5590e Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Tue, 24 Jun 2025 23:14:09 +0100 Subject: [PATCH 12/32] update: tests formatAs12HourClock function for as many different groups of input data or edge cases as you can, and fix any bugs in Sprint-2/5-stretch-extend/format-time.js --- Sprint-2/5-stretch-extend/format-time.js | 47 +++++++++++++++++++++--- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/Sprint-2/5-stretch-extend/format-time.js b/Sprint-2/5-stretch-extend/format-time.js index 32a32e66b..7f223ccb5 100644 --- a/Sprint-2/5-stretch-extend/format-time.js +++ b/Sprint-2/5-stretch-extend/format-time.js @@ -3,23 +3,60 @@ // 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`; + // If hours is less than 12, it should be am + const [hourStr, minute] = time.split(":"); + let hours = Number(hourStr); + let suffix = "am"; + // If hours is 0, it should be 12 am + if (hours === 0) { + hours = 12; } - return `${time} am`; + // If hours is less than 12, it should be am + else if (hours === 12) { + suffix = "pm"; + } + // If hours is greater than 12, it should be pm + else if (hours > 12) { + hours -= 12; + suffix = "pm"; + } + //return `${time} am`; ignoring the actual minutes + const paddedHour = String(hours).padStart(2, "0"); + return `${paddedHour}:${minute} ${suffix}`; } +// test 1 const currentOutput = formatAs12HourClock("08:00"); const targetOutput = "08:00 am"; console.assert( currentOutput === targetOutput, `current output: ${currentOutput}, target output: ${targetOutput}` ); - +// test 2 const currentOutput2 = formatAs12HourClock("23:00"); const targetOutput2 = "11:00 pm"; console.assert( currentOutput2 === targetOutput2, `current output: ${currentOutput2}, target output: ${targetOutput2}` ); +// test3 +const currentOutput3 = formatAs12HourClock("12:00"); +const targetOutput3 = "12:00 pm"; +console.assert( + currentOutput3 === targetOutput3, + `current output: ${currentOutput3}, target output: ${targetOutput3}` +); +//test 4 +const currentOutput4 = formatAs12HourClock("14:45"); +const targetOutput4 = "02:45 pm"; +console.assert( + currentOutput4 === targetOutput4, + `current output: ${currentOutput4}, target output: ${targetOutput4}` +); +// test 5 +const currentOutput5 = formatAs12HourClock("01:00"); +const targetOutput5 = "01:00 am"; +console.assert( + currentOutput5 === targetOutput5, + `current output: ${currentOutput5}, target output: ${targetOutput5}` +); From ba7c34810b3e6f7d9b1325ccfecdfc61236f76c8 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 00:44:36 +0100 Subject: [PATCH 13/32] update: Implement angle type identification in getAngleType function --- Sprint-3/1-key-implement/1-get-angle-type.js | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/Sprint-3/1-key-implement/1-get-angle-type.js b/Sprint-3/1-key-implement/1-get-angle-type.js index 08d1f0cba..49185fded 100644 --- a/Sprint-3/1-key-implement/1-get-angle-type.js +++ b/Sprint-3/1-key-implement/1-get-angle-type.js @@ -8,8 +8,16 @@ // Then, write the next test! :) Go through this process until all the cases are implemented function getAngleType(angle) { - if (angle === 90) return "Right angle"; - // read to the end, complete line 36, then pass your test here + if (angle === 90) return "Right angle"; + // read to the end, complete line 36, then pass your test here + // if the angle is less than 90, return "Acute angle" + if (angle < 90) return "Acute angle"; + // if the angle is greater than 90 and less than 180, return "Obtuse angle" + if (angle > 90 && angle < 180) return "Obtuse angle"; + // if the angle is exactly 180, return "Straight angle" + if (angle === 180) return "Straight angle"; + // if the angle is greater than 180 and less than 360, return "Reflex angle" + if (angle > 180 && angle < 360) return "Reflex angle"; } // we're going to use this helper function to make our assertions easier to read @@ -43,14 +51,19 @@ assertEquals(acute, "Acute angle"); // When the angle is greater than 90 degrees and less than 180 degrees, // Then the function should return "Obtuse angle" const obtuse = getAngleType(120); +assertEquals(obtuse, "Obtuse angle"); // ====> write your test here, and then add a line to pass the test in the function above // Case 4: Identify Straight Angles: // When the angle is exactly 180 degrees, // Then the function should return "Straight angle" // ====> write your test here, and then add a line to pass the test in the function above +const straightAngle = getAngleType(180); +assertEquals(straightAngle, "Straight angle"); // Case 5: Identify Reflex Angles: // When the angle is greater than 180 degrees and less than 360 degrees, // Then the function should return "Reflex angle" -// ====> write your test here, and then add a line to pass the test in the function above \ No newline at end of file +// ====> write your test here, and then add a line to pass the test in the function above +const reflex = getAngleType(270); +assertEquals(reflex, "Reflex angle"); From e6d6e766bc49146536b717eba1e4bae3130555a0 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 00:46:09 +0100 Subject: [PATCH 14/32] UPdate: fix isProperFraction function to handle negative numbers and add tests for zero numerator and denominator --- .../1-key-implement/2-is-proper-fraction.js | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/Sprint-3/1-key-implement/2-is-proper-fraction.js b/Sprint-3/1-key-implement/2-is-proper-fraction.js index 91583e941..25112cb4a 100644 --- a/Sprint-3/1-key-implement/2-is-proper-fraction.js +++ b/Sprint-3/1-key-implement/2-is-proper-fraction.js @@ -8,7 +8,8 @@ // write one test at a time, and make it pass, build your solution up methodically function isProperFraction(numerator, denominator) { - if (numerator < denominator) return true; + // if (numerator < denominator) return true; it will not work for negative numbers + return Math.abs(numerator) < Math.abs(denominator); } // here's our helper again @@ -41,6 +42,7 @@ assertEquals(improperFraction, false); // Explanation: The fraction -4/7 is a proper fraction because the absolute value of the numerator (4) is less than the denominator (7). The function should return true. const negativeFraction = isProperFraction(-4, 7); // ====> complete with your assertion +assertEquals(negativeFraction, true); // Equal Numerator and Denominator check: // Input: numerator = 3, denominator = 3 @@ -48,6 +50,20 @@ const negativeFraction = isProperFraction(-4, 7); // Explanation: The fraction 3/3 is not a proper fraction because the numerator is equal to the denominator. The function should return false. const equalFraction = isProperFraction(3, 3); // ====> complete with your assertion - +assertEquals(equalFraction, false); // Stretch: // What other scenarios could you test for? + +// Zero Numerator check: +// Input: numerator = 0, denominator = 5 +// target output: true +// Explanation: The fraction 0/5 is a proper fraction because the numerator (0) is less than the denominator (5). The function should return true. +const zeroNumerator = isProperFraction(0, 5); +assertEquals(zeroNumerator, true); + +// Zero Denominator check: +// Input: numerator = 4, denominator = 0 +// target output: false +// Explanation: A fraction with a zero denominator is undefined. The function should return false to indicate it's not a valid proper fraction. +const zeroDenominator = isProperFraction(4, 0); +assertEquals(zeroDenominator, false); From cea35124a866e7b2929d573a6a105562a5b23371 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 00:47:06 +0100 Subject: [PATCH 15/32] Update: fix getCardValue function to handle face cards, numeric ranks, and invalid inputs with corresponding tests --- Sprint-3/1-key-implement/3-get-card-value.js | 39 +++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/Sprint-3/1-key-implement/3-get-card-value.js b/Sprint-3/1-key-implement/3-get-card-value.js index aa1cc9f90..7bebb6e1a 100644 --- a/Sprint-3/1-key-implement/3-get-card-value.js +++ b/Sprint-3/1-key-implement/3-get-card-value.js @@ -8,7 +8,22 @@ // write one test at a time, and make it pass, build your solution up methodically // just make one change at a time -- don't rush -- programmers are deep and careful thinkers function getCardValue(card) { - if (rank === "A") return 11; + const rank = card.slice(0, -1); // Extract the rank from the card string + + if (rank === "A") return 11; + + // Face cards and 10 are worth 10 points + if (["10", "J", "Q", "K"].includes(rank)) { + return 10; + } + // Convert rank to number and check if it's a valid number card + const numericRank = Number(rank); + if (!isNaN(numericRank)) { + return numericRank; + } + // If rank is not valid, throw an error + throw new Error("Invalid card rank."); + // Note: The function assumes the input is always a valid card string } // You need to write assertions for your function to check it works in different cases @@ -34,18 +49,40 @@ assertEquals(aceofSpades, 11); // Then it should return the numeric value corresponding to the rank (e.g., "5" should return 5). const fiveofHearts = getCardValue("5♥"); // ====> write your test here, and then add a line to pass the test in the function above +assertEquals(fiveofHearts, 5); // 5 of Hearts should return 5 but still we need to implement this in the function // Handle Face Cards (J, Q, K): // Given a card with a rank of "10," "J," "Q," or "K", // When the function is called with such a card, // Then it should return the value 10, as these cards are worth 10 points each in blackjack. +const tenOfDiamonds = getCardValue("10♦"); +assertEquals(tenOfDiamonds, 10); // 10 of Diamonds should return 10 +const jackOfClubs = getCardValue("J♣"); +assertEquals(jackOfClubs, 10); // Jack of Clubs should return 10 +const queenOfSpades = getCardValue("Q♠"); +assertEquals(queenOfSpades, 10); // Queen of Spades should return 10 +const kingOfHearts = getCardValue("K♥"); +assertEquals(kingOfHearts, 10); // King of Hearts should return 10 // Handle Ace (A): // Given a card with a rank of "A", // When the function is called with an Ace, // Then it should, by default, assume the Ace is worth 11 points, which is a common rule in blackjack. +const aceOfDiamonds = getCardValue("A♦"); +assertEquals(aceOfDiamonds, 11); // Ace of Diamonds should return 11 + // Handle Invalid Cards: // Given a card with an invalid rank (neither a number nor a recognized face card), // When the function is called with such a card, // Then it should throw an error indicating "Invalid card rank." +// Invalid card test (should throw error) +try { + getCardValue("Z♠"); + console.assert(false, "Expected error for invalid rank"); +} catch (e) { + console.assert( + e.message === "Invalid card rank.", + `Unexpected error message: ${e.message}` + ); +} From d375cee33eaa4869d57fd040176763dbfe51ae3f Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 00:53:40 +0100 Subject: [PATCH 16/32] Update: fix getAngleType function to improve readability and ensure proper angle classification with consolelog --- .../2-mandatory-rewrite/1-get-angle-type.js | 31 ++++++++++++++----- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js b/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js index d61254bd7..0e5e3f435 100644 --- a/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js +++ b/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js @@ -1,18 +1,33 @@ function getAngleType(angle) { - if (angle === 90) return "Right angle"; // replace with your completed function from key-implement + // Step 1: Check for a right angle (exactly 90 degrees) + if (angle === 90) return "Right angle"; -} - - - - + // Step 2: Check for a straight angle (exactly 180 degrees) + if (angle === 180) return "Straight angle"; + // Step 3: Check for an acute angle (between 0 and 90) + if (angle > 0 && angle < 90) return "Acute Angle"; + // Step 4: Check for an obtuse angle (between 90 and 180) + if (angle > 90 && angle < 180) return "Obtuse angle"; + // Step 5: Check for a reflex angle (between 180 and 360) + if (angle > 180 && angle < 360) return "Reflex angle"; + // Step 6: Handle invalid or unsupported input + return "Invalid angle"; +} // Don't get bogged down in this detail // Jest uses CommonJS module syntax by default as it's quite old -// We will upgrade our approach to ES6 modules in the next course module, so for now +// We will upgrade our approach to ES6 modules in the next course module, so for now // we have just written the CommonJS module.exports syntax for you -module.exports = getAngleType; \ No newline at end of file +module.exports = getAngleType; + +console.log(getAngleType(90)); // "Right angle" +console.log(getAngleType(180)); // "Straight angle" +console.log(getAngleType(45)); // "Acute angle" +console.log(getAngleType(120)); // "Obtuse angle" +console.log(getAngleType(0)); // "Invalid angle" +console.log(getAngleType(200)); // "Invalid angle" +console.log(getAngleType(90.5)); // "Invalid angle" From f66a15ad5b41d42bd7003e15fb5e91171b769afb Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 00:55:06 +0100 Subject: [PATCH 17/32] Update: fix and test descriptions for angle type identification for clarity and readability --- .../1-get-angle-type.test.js | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/Sprint-3/2-mandatory-rewrite/1-get-angle-type.test.js b/Sprint-3/2-mandatory-rewrite/1-get-angle-type.test.js index b62827b7c..2d41f61ea 100644 --- a/Sprint-3/2-mandatory-rewrite/1-get-angle-type.test.js +++ b/Sprint-3/2-mandatory-rewrite/1-get-angle-type.test.js @@ -1,24 +1,31 @@ -const getAngleType = require("./1-get-angle-type"); +const getAngleType = require("./1-get-angle-type"); // Import the function to be tested test("should identify right angle (90°)", () => { expect(getAngleType(90)).toEqual("Right angle"); }); -// REPLACE the comments with the tests -// make your test descriptions as clear and readable as possible - // Case 2: Identify Acute Angles: // When the angle is less than 90 degrees, // Then the function should return "Acute angle" +test("should identify Acute Angles (< 90)", () => { + expect(getAngleType(45)).toEqual("Acute Angle"); +}); // Case 3: Identify Obtuse Angles: // When the angle is greater than 90 degrees and less than 180 degrees, // Then the function should return "Obtuse angle" - +test("should identify Obtuse angle (>90 && <180)", () => { + expect(getAngleType(120)).toEqual("Obtuse angle"); +}); // Case 4: Identify Straight Angles: // When the angle is exactly 180 degrees, // Then the function should return "Straight angle" - +test("should identify Straight Angle (180°)", () => { + expect(getAngleType(180)).toEqual("Straight angle"); +}); // Case 5: Identify Reflex Angles: // When the angle is greater than 180 degrees and less than 360 degrees, // Then the function should return "Reflex angle" +test("should identify Straight Angle (> 180 && < 360)", () => { + expect(getAngleType(278)).toEqual("Reflex angle"); +}); From e67b16269e7a99a287c154788a2baa7c5eed4f08 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 00:55:30 +0100 Subject: [PATCH 18/32] Update: comment out example console logs in getAngleType function for cleaner code --- Sprint-3/2-mandatory-rewrite/1-get-angle-type.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js b/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js index 0e5e3f435..d2e6b06e2 100644 --- a/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js +++ b/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js @@ -24,10 +24,10 @@ function getAngleType(angle) { // we have just written the CommonJS module.exports syntax for you module.exports = getAngleType; -console.log(getAngleType(90)); // "Right angle" -console.log(getAngleType(180)); // "Straight angle" -console.log(getAngleType(45)); // "Acute angle" -console.log(getAngleType(120)); // "Obtuse angle" -console.log(getAngleType(0)); // "Invalid angle" -console.log(getAngleType(200)); // "Invalid angle" -console.log(getAngleType(90.5)); // "Invalid angle" +// console.log(getAngleType(90)); // "Right angle" +// console.log(getAngleType(180)); // "Straight angle" +// console.log(getAngleType(45)); // "Acute angle" +// console.log(getAngleType(120)); // "Obtuse angle" +// console.log(getAngleType(0)); // "Invalid angle" +// console.log(getAngleType(200)); // "Invalid angle" +// console.log(getAngleType(90.5)); // "Invalid angle" From 0a7cda4234d2fb0be1594c08b6116592c90b62e8 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 00:56:33 +0100 Subject: [PATCH 19/32] Update: test isProperFraction function to include comprehensive checks for numerator and denominator, ensuring proper fraction validation --- .../2-is-proper-fraction.js | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.js b/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.js index 9836fe398..90315e03c 100644 --- a/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.js +++ b/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.js @@ -1,6 +1,19 @@ function isProperFraction(numerator, denominator) { - if (numerator < denominator) return true; - // add your completed function from key-implement here + if (denominator === 0) return false; // Avoid division by zero + if (numerator < 0 || denominator < 0) return false; // Proper fractions are positive + if (numerator < denominator) return true; // Proper if numerator < denominator + return false; // Otherwise, it's improper } -module.exports = isProperFraction; \ No newline at end of file +module.exports = isProperFraction; +// Test cases for the isProperFraction function +console.log(isProperFraction(1, 2)); // true +console.log(isProperFraction(3, 4)); // true +console.log(isProperFraction(5, 5)); // false +console.log(isProperFraction(7, 6)); // false +console.log(isProperFraction(0, 1)); // true +console.log(isProperFraction(1, 0)); // false (denominator is zero) +console.log(isProperFraction(-1, 2)); // false (negative numerator) +console.log(isProperFraction(1, -2)); // false (negative denominator) +console.log(isProperFraction(-1, -2)); // false (both negative) +console.log(isProperFraction(2, 3)); // true From 87fc686cad6f75ccdc833dc3c2f752c550394866 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 00:58:28 +0100 Subject: [PATCH 20/32] Update: test isProperFraction function is correct and reintroduce usage examples --- .../2-is-proper-fraction.test.js | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.test.js b/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.test.js index ff1cc8173..022627492 100644 --- a/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.test.js +++ b/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.test.js @@ -1,11 +1,27 @@ -const isProperFraction = require("./2-is-proper-fraction"); +function isProperFraction(numerator, denominator) { + // Case 1: Check for zero denominator (undefined) + if (denominator === 0) return false; -test("should return true for a proper fraction", () => { - expect(isProperFraction(2, 3)).toEqual(true); -}); + // Case 2: Check for negative values (numerator or denominator) + if (numerator < 0 || denominator < 0) return false; -// Case 2: Identify Improper Fractions: + // Case 3: Check for equal numerator and denominator + if (numerator === denominator) return false; -// Case 3: Identify Negative Fractions: + // Case 4: Check for proper fraction (numerator < denominator) + return numerator < denominator; +} +module.exports = isProperFraction; +// usage examples +console.log(isProperFraction(2, 3)); // true +console.log(isProperFraction(5, 3)); // false +console.log(isProperFraction(3, 3)); // false +console.log(isProperFraction(-2, 3)); // false +console.log(isProperFraction(2, -3)); // false +console.log(isProperFraction(0, 5)); // true (0 < 5) +console.log(isProperFraction(2, 2)); // false -// Case 4: Identify Equal Numerator and Denominator: +// Test cases for the isProperFraction function +// test("should return true for a proper fraction", () => { +// expect(isProperFraction(2, 3)).toEqual(true); +// }); From a52f2c1fdee5a4c7d24bd06d84666a37cce58650 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 00:59:28 +0100 Subject: [PATCH 21/32] Update: implement getCardValue function to return correct card values and add test cases --- .../2-mandatory-rewrite/3-get-card-value.js | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/Sprint-3/2-mandatory-rewrite/3-get-card-value.js b/Sprint-3/2-mandatory-rewrite/3-get-card-value.js index 0d95d3736..41c123a75 100644 --- a/Sprint-3/2-mandatory-rewrite/3-get-card-value.js +++ b/Sprint-3/2-mandatory-rewrite/3-get-card-value.js @@ -1,5 +1,20 @@ function getCardValue(card) { - // replace with your code from key-implement - return 11; + // replace with your code from key-implement + // return 11; // always return 11 for testing purposes that is wrong + const rank = card.slice(0, -1); // Extract rank (everything except the last character) + if (rank === "A") return 11; // handle Ace as 11 + if (["K", "Q", "J"].includes(rank)) return 10; // handle face cards as 10 + const numerincRank = parseInt(rank); //Handle number cards 2–9 + if (numerincRank >= 2 && numerincRank <= 9) { + return numerincRank; // Return the numeric value for cards 2-9 + } + // Invalid card rank + return 0; } -module.exports = getCardValue; \ No newline at end of file +module.exports = getCardValue; + +// // Test cases +console.log(getCardValue("A♠")); // 11 +console.log(getCardValue("7♥")); // 7 +console.log(getCardValue("K♦")); // 10 +console.log(getCardValue("A♣")); // 11 From e2c54d6df8b5656fdc98b4c8469e0d4ab8058118 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 01:00:14 +0100 Subject: [PATCH 22/32] Update: fix test cases in getCardValue to improve readability and consistency --- .../3-get-card-value.test.js | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/Sprint-3/2-mandatory-rewrite/3-get-card-value.test.js b/Sprint-3/2-mandatory-rewrite/3-get-card-value.test.js index 03a8e2f34..a82316add 100644 --- a/Sprint-3/2-mandatory-rewrite/3-get-card-value.test.js +++ b/Sprint-3/2-mandatory-rewrite/3-get-card-value.test.js @@ -1,11 +1,27 @@ const getCardValue = require("./3-get-card-value"); test("should return 11 for Ace of Spades", () => { - const aceofSpades = getCardValue("A♠"); - expect(aceofSpades).toEqual(11); - }); + const aceofSpades = getCardValue("A♠"); + expect(aceofSpades).toEqual(11); +}); // Case 2: Handle Number Cards (2-10): +test("should return 7 for 7 of Hearts", () => { + const sevenOfHearts = getCardValue("7♥"); + expect(sevenOfHearts).toEqual(7); +}); // Case 3: Handle Face Cards (J, Q, K): +test("should return 10 for King of Diamonds", () => { + const kingOfDiamonds = getCardValue("K♦"); + expect(kingOfDiamonds).toEqual(10); +}); // Case 4: Handle Ace (A): +test("should return 11 for Ace of Clubs", () => { + const aceOfClubs = getCardValue("A♣"); + expect(aceOfClubs).toEqual(11); +}); // Case 5: Handle Invalid Cards: +test("should return 0 for invalid card 'X♠'", () => { + const invalidCard = getCardValue("X♠"); + expect(invalidCard).toEqual(0); +}); From 101471404a2b321b9d7f11453902828635b0c50a Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 01:06:24 +0100 Subject: [PATCH 23/32] Update: fix countChar function with correct implementation and add example usage --- Sprint-3/3-mandatory-practice/implement/count.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Sprint-3/3-mandatory-practice/implement/count.js b/Sprint-3/3-mandatory-practice/implement/count.js index fce249650..2b056aa25 100644 --- a/Sprint-3/3-mandatory-practice/implement/count.js +++ b/Sprint-3/3-mandatory-practice/implement/count.js @@ -1,5 +1,11 @@ function countChar(stringOfCharacters, findCharacter) { - return 5 + // return 5; //This will always return 5, regardless of the inputs. So it’s just a placeholder. + return stringOfCharacters.split(findCharacter).length - 1; } -module.exports = countChar; \ No newline at end of file +module.exports = countChar; + +// console.log(countChar("hello", "l")); // 2 +// console.log(countChar("hello world", "o")); // 2 +// console.log(countChar("banana", "a")); // 3 +// console.log(countChar("mississippi", "i")); // 5 From af666321b16db7b5d4aaa6c54550db4ba539837f Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 01:08:51 +0100 Subject: [PATCH 24/32] Update: add test case for countChar function to verify function --- Sprint-3/3-mandatory-practice/implement/count.test.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Sprint-3/3-mandatory-practice/implement/count.test.js b/Sprint-3/3-mandatory-practice/implement/count.test.js index 42baf4b4b..165467d59 100644 --- a/Sprint-3/3-mandatory-practice/implement/count.test.js +++ b/Sprint-3/3-mandatory-practice/implement/count.test.js @@ -22,3 +22,11 @@ test("should count multiple occurrences of a character", () => { // And a character char that does not exist within the case-sensitive str, // When the function is called with these inputs, // Then it should return 0, indicating that no occurrences of the char were found in the case-sensitive str. +test("should return 0 when the character is not present", () => { + const str = "aaaaa"; + const char = "z"; // 'z' does not exist in "aaaaa" + const count = countChar(str, char); + expect(count).toEqual(0); +}); + +module.exports = countChar; From a5879e7f3e45c497dec5599aeb34429984b6f04c Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 01:09:44 +0100 Subject: [PATCH 25/32] Update: implement getOrdinalNumber function to return correct ordinal numbers --- .../implement/get-ordinal-number.js | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.js b/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.js index 24f528b0d..2c5d0e882 100644 --- a/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.js +++ b/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.js @@ -1,5 +1,28 @@ function getOrdinalNumber(num) { - return "1st"; + // return "1st"; //always returns "1st" no matter what input is provided + const lastTwo = num % 100; + const lastDigit = num % 10; + if (lastTwo >= 11 && lastTwo <= 13) { + return num + "th"; + } + + switch (lastDigit) { + case 1: + return num + "st"; + case 2: + return num + "nd"; + case 3: + return num + "rd"; + default: + return num + "th"; + } } +module.exports = getOrdinalNumber; -module.exports = getOrdinalNumber; \ No newline at end of file +// console.log(getOrdinalNumber(1)); // "1st" +// console.log(getOrdinalNumber(2)); // "2nd" +// console.log(getOrdinalNumber(3)); // "3rd" +// console.log(getOrdinalNumber(4)); // "4th" +// console.log(getOrdinalNumber(51)); // "51st" +// console.log(getOrdinalNumber(102)); // "102nd" +// console.log(getOrdinalNumber(1114)); // "1114th" From e255a25cc9418f3b1aea884f081f6aaafca7e5b5 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 01:12:00 +0100 Subject: [PATCH 26/32] Update: fix code and test in getOrdinalNumber test case --- .../implement/get-ordinal-number.test.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.test.js b/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.test.js index 6d55dfbb4..dfa8e44b6 100644 --- a/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.test.js +++ b/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.test.js @@ -9,5 +9,6 @@ const getOrdinalNumber = require("./get-ordinal-number"); // Then the function should return "1st" test("should return '1st' for 1", () => { - expect(getOrdinalNumber(1)).toEqual("1st"); - }); + expect(getOrdinalNumber(1)).toEqual("1st"); +}); +console.log(getOrdinalNumber(1)); From 9b9d6facf12672482b44b2c38619d7ade6f6857d Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 01:13:10 +0100 Subject: [PATCH 27/32] Update: fix repeat function to accept parameters and handle non-negative integer counts --- .../3-mandatory-practice/implement/repeat.js | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/Sprint-3/3-mandatory-practice/implement/repeat.js b/Sprint-3/3-mandatory-practice/implement/repeat.js index 621f9bd35..ace324344 100644 --- a/Sprint-3/3-mandatory-practice/implement/repeat.js +++ b/Sprint-3/3-mandatory-practice/implement/repeat.js @@ -1,5 +1,19 @@ -function repeat() { - return "hellohellohello"; +// function repeat() { +// return "hellohellohello"; +// } +// The function always returns "hellohellohello" regardless of any input. +// There are no parameters, so it’s not flexible or reusable. +function repeat(str, count) { + if (!Number.isInteger(count) || count < 0) { + return "Error: Count must be a non-negative integer"; + } + return str.repeat(count); } -module.exports = repeat; \ No newline at end of file +module.exports = repeat; +// Example usage: +// console.log(repeat("hello", 3)); // Expected: "hellohellohello" +// console.log(repeat("at", 5)); // Expected: "atatatatat" +// console.log(repeat("test0", 0)); // Expected: "" +// console.log(repeat("", 5)); // Expected: "" +// console.log(repeat("WE", 1)); // Expected: "hi" From 4c03b27739a6e40b289ef452aad5f9d8cba418a2 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 01:13:54 +0100 Subject: [PATCH 28/32] Update: test cases in repeat.test.js for clarity --- .../implement/repeat.test.js | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Sprint-3/3-mandatory-practice/implement/repeat.test.js b/Sprint-3/3-mandatory-practice/implement/repeat.test.js index 8a4ab42ef..2df825f68 100644 --- a/Sprint-3/3-mandatory-practice/implement/repeat.test.js +++ b/Sprint-3/3-mandatory-practice/implement/repeat.test.js @@ -9,24 +9,25 @@ const repeat = require("./repeat"); // When the repeat function is called with these inputs, // Then it should repeat the str count times and return a new string containing the repeated str values. -test("should repeat the string count times", () => { - const str = "hello"; - const count = 3; - const repeatedStr = repeat(str, count); - expect(repeatedStr).toEqual("hellohellohello"); - }); +// test("should repeat the string count times", () => { +// const str = "hello"; +// const count = 3; +// const repeatedStr = repeat(str, count); +// expect(repeatedStr).toEqual("hellohellohello"); +// }); // case: handle Count of 1: // Given a target string str and a count equal to 1, // When the repeat function is called with these inputs, // Then it should return the original str without repetition, ensuring that a count of 1 results in no repetition. - +console.log(repeat("str", 1)); // Expected: "str" // case: Handle Count of 0: // Given a target string str and a count equal to 0, // When the repeat function is called with these inputs, // Then it should return an empty string, ensuring that a count of 0 results in an empty output. - +console.log(repeat("hello", 0)); // Expected: " " // case: Negative Count: // Given a target string str and a negative integer count, // When the repeat function is called with these inputs, // Then it should throw an error or return an appropriate error message, as negative counts are not valid. +console.log(repeat("hello", -3)); // Expected: "Error: Count must be a non-negative integer" From d0371be7fe7131c7a621be0fdd1287c72df9f79c Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 01:15:55 +0100 Subject: [PATCH 29/32] Update: comments foe questions to explain code in find.js for better clarity on loop mechanics --- Sprint-3/4-stretch-investigate/find.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Sprint-3/4-stretch-investigate/find.js b/Sprint-3/4-stretch-investigate/find.js index c7e79a2f2..4e16197dc 100644 --- a/Sprint-3/4-stretch-investigate/find.js +++ b/Sprint-3/4-stretch-investigate/find.js @@ -20,6 +20,11 @@ console.log(find("code your future", "z")); // Pay particular attention to the following: // a) How the index variable updates during the call to find +// increments by 1 in every iteration using index++. // b) What is the if statement used to check +// checks if the character at the current index matches the specified character. // c) Why is index++ being used? +// It moves the pointer forward through the string. Without it, the loop would run infinitely. + // d) What is the condition index < str.length used for? +// It ensures we don’t read beyond the string boundary — this prevents errors or undefined behavior. From 094657bc23febf37ba2a07180af1b886556b5ead Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 01:17:26 +0100 Subject: [PATCH 30/32] Update: fix password validation logic and comment out test cases --- .../password-validator.js | 34 ++++++++++++++++--- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/Sprint-3/4-stretch-investigate/password-validator.js b/Sprint-3/4-stretch-investigate/password-validator.js index b55d527db..381851b87 100644 --- a/Sprint-3/4-stretch-investigate/password-validator.js +++ b/Sprint-3/4-stretch-investigate/password-validator.js @@ -1,6 +1,32 @@ -function passwordValidator(password) { - return password.length < 5 ? false : true -} +// function passwordValidator(password) { +// return password.length < 5 ? false : true; +// } + +// module.exports = passwordValidator; +const previousPasswords = ["Password123!", "Welcome2023$", "Admin*1"]; +function isValidPassword(password) { + const hasMinLength = password.length >= 5; + const hasUppercase = /[A-Z]/.test(password); + const hasLowercase = /[a-z]/.test(password); + const hasDigit = /[0-9]/.test(password); + const hasSymbol = /[!#$%.*&]/.test(password); + const isNotPrevious = !previousPasswords.includes(password); + + return ( + hasMinLength && + hasUppercase && + hasLowercase && + hasDigit && + hasSymbol && + isNotPrevious + ); +} -module.exports = passwordValidator; \ No newline at end of file +module.exports = isValidPassword; +// Example usage: +// console.log(isValidPassword("Abdi10!")); // true +// console.log(isValidPassword("12345")); // false +// console.log(isValidPassword("123")); // false +// console.log(isValidPassword("abcde")); // false +// console.log(isValidPassword("")); // false From d457ddd28613730756e077931189100dec491ae9 Mon Sep 17 00:00:00 2001 From: SuWebOnes Date: Thu, 3 Jul 2025 01:19:00 +0100 Subject: [PATCH 31/32] Update: password validation test for consistency and clarity --- .../password-validator.test.js | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/Sprint-3/4-stretch-investigate/password-validator.test.js b/Sprint-3/4-stretch-investigate/password-validator.test.js index 8fa3089d6..d67f22d2d 100644 --- a/Sprint-3/4-stretch-investigate/password-validator.test.js +++ b/Sprint-3/4-stretch-investigate/password-validator.test.js @@ -16,11 +16,16 @@ You must breakdown this problem in order to solve it. Find one test case first a */ const isValidPassword = require("./password-validator"); test("password has at least 5 characters", () => { - // Arrange - const password = "12345"; - // Act - const result = isValidPassword(password); - // Assert - expect(result).toEqual(true); -} -); \ No newline at end of file + // Arrange + const password = "12345"; + // Act + const result = isValidPassword(password); + // Assert + expect(result).toEqual(true); +}); +expect(result).toEqual(true); +const isValidPassword = require("./password-validator"); +// // usage example +// console.log(isValidPassword("Test123!")); // true +// console.log(isValidPassword("pass")); // false (too short) +// console.log(isValidPassword("password")); // false (no number or special character) From ec2b4c0e4c8695cd93c8496af1c5d234eb8bb26c Mon Sep 17 00:00:00 2001 From: Surafel Date: Mon, 7 Jul 2025 21:32:59 +0100 Subject: [PATCH 32/32] Revert "London | May-2025 | Surafel Workneh | Acoursework/sprint 2" --- Sprint-2/1-key-errors/0.js | 23 ++------- Sprint-2/1-key-errors/1.js | 33 +++---------- Sprint-2/1-key-errors/2.js | 22 ++++----- Sprint-2/2-mandatory-debug/0.js | 20 +------- Sprint-2/2-mandatory-debug/1.js | 17 ++----- Sprint-2/2-mandatory-debug/2.js | 29 ++++-------- Sprint-2/3-mandatory-implement/1-bmi.js | 14 +----- Sprint-2/3-mandatory-implement/2-cases.js | 33 ------------- Sprint-2/3-mandatory-implement/3-to-pounds.js | 29 ------------ Sprint-2/4-mandatory-interpret/time-format.js | 13 ++--- Sprint-2/5-stretch-extend/format-time.js | 47 ++----------------- 11 files changed, 46 insertions(+), 234 deletions(-) diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js index 36cdb5dc3..653d6f5a0 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -4,25 +4,10 @@ // 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; -// } - -// =============> write your explanation here -// The function capitalize is trying to take a string input and return it with the first letter capitalized. -// However, the error occurs because the variable 'str' is being declared twice: once as a parameter and again inside the function. -// This is not allowed in JavaScript, as 'let' does not allow redeclaration of the same variable in the same scope. -// This causes a syntax error because you cannot redeclare a variable with 'let' in the same scope. -// =============> write your new code here - function capitalise(str) { - let name = `${str[0].toUpperCase()}${str.slice(1)}`; - return name; + let str = `${str[0].toUpperCase()}${str.slice(1)}`; + return str; } -capitalise("hello, check "); -console.log(capitalise("hello, check ")); + // =============> write your explanation here -// The function now uses a different variable name 'name' instead of 'str' inside the function. -// This avoids the redeclaration error. The function takes a string input, capitalizes the first letter, and returns the modified string. -// However, the return statement still returns 'str' instead of 'name', which is a mistake. +// =============> write your new code here diff --git a/Sprint-2/1-key-errors/1.js b/Sprint-2/1-key-errors/1.js index 723a872f1..f2d56151f 100644 --- a/Sprint-2/1-key-errors/1.js +++ b/Sprint-2/1-key-errors/1.js @@ -5,35 +5,16 @@ // Try playing computer with the example to work out what is going on -// function convertToPercentage(decimalNumber) { -// const decimalNumber = 0.5; -// The above line will cause an error because 'decimalNumber' is being redeclared with 'const' -// after it has already been defined as a parameter of the function. -// This will result in a SyntaxError: Identifier 'decimalNumber' has already been declared. -// it is trying to declare a new constant variable with the same name as the parameter of the function: decimalNumber -// const percentage = `${decimalNumber * 100}%`; -// The above line correctly converts the decimal number to a percentage by multiplying it by 100 -// and appending a '%' sign. -// However, the function will not execute due to the redeclaration error. - -// return percentage; -// // } - -// console.log(decimalNumber); -// console.log(decimalNumber) outside the function — but decimalNumber was only defined inside the function. -// =============> write your explanation here - -// Finally, correct the code to fix the problem -// =============> write your new code here function convertToPercentage(decimalNumber) { + const decimalNumber = 0.5; const percentage = `${decimalNumber * 100}%`; + return percentage; } + +console.log(decimalNumber); + // =============> write your explanation here -// The function now correctly takes a decimal number as input, converts it to a percentage by multiplying it by 100, -// and returns the result as a string with a '%' sign appended. The redeclaration error has been fixed by removing the -// unnecessary declaration of 'decimalNumber' inside the function. The function can now be called with a decimal number, -// and it will return the corresponding percentage string. -console.log(convertToPercentage(0.5)); // "50%" -// The function now works correctly and returns the expected output without any errors. +// Finally, correct the code to fix the problem +// =============> write your new code here diff --git a/Sprint-2/1-key-errors/2.js b/Sprint-2/1-key-errors/2.js index 84ec2dad9..aad57f7cf 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -1,26 +1,20 @@ + // Predict and explain first BEFORE you run any code... -// the will be an error -// this function should square any number but instead we're going to get an error -// Why will an error occur when this program runs? -//because the function parameter is incorrectly defined by real number instead of a variable name +// 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; +} // =============> write the error message here -//syntaxError: Unexpected number + // =============> explain this error message here -// The error occurs because the function parameter is defined as a number (3) instead of a variable name. -// In JavaScript, function parameters must be variable names, not literal values. JavaScript is expecting a parameter name in the parentheses, not a value. + // Finally, correct the code to fix the problem // =============> write your new code here -function square(num) { - return num * num; -} -console.log(square(3)); // This will not work because 'num' is not defined outside the function + diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js index 2b688059e..b27511b41 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -1,30 +1,14 @@ // Predict and explain first... -// The code below is intended to multiply two numbers and log the result. -// However, it currently does not return the result correctly. -// The function `multiply` is defined to take two parameters `a` and `b`. -// It logs the product of `a` and `b` but does not return it. -// The console.log statement outside the function attempts to log the result of calling `multiply(10, 32)`. -// The expected output is "The result of multiplying 10 and 32 is 320". -// However, since `multiply` does not return a value, the output will be "The result of multiplying 10 and 32 is undefined". // =============> write your prediction here function multiply(a, b) { - // This function multiplies two numbers and logs the result - // but does not return it. - // It should return the product instead of just logging it. - // The current implementation will not return the product. - //console.log(a * b); - // This line should be changed to return the product - return a * b; // Corrected to return the product + console.log(a * b); } console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); + // =============> write your explanation here -// // The code is intended to multiply two numbers and log the result. -// However, it currently does not return the result correctly. -// The expected output is "The result of multiplying 10 and 32 is 320". -// The current output will be "The result of multiplying 10 and 32 is undefined". // 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 06e6c7e84..37cedfbcf 100644 --- a/Sprint-2/2-mandatory-debug/1.js +++ b/Sprint-2/2-mandatory-debug/1.js @@ -1,20 +1,13 @@ // Predict and explain first... // =============> write your prediction here -// The sum of 10 and 32 is 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 -// The function called `sum` is defined to take two parameters `a` and `b`, but it does not return the result of adding them together. -// Instead, it has a `return` statement which exits the function without returning any value. // Finally, correct the code to fix the problem // =============> write your new code here -function sum(a, b) { - return a + b; -} -console.log(sum(10, 32)); diff --git a/Sprint-2/2-mandatory-debug/2.js b/Sprint-2/2-mandatory-debug/2.js index f3d78fc1e..57d3f5dc3 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -1,37 +1,24 @@ // Predict and explain first... -// This code is intended to find the last digit of a number, but it has a bug. // Predict the output of the following code: -// Predict the output of the following code is '3' for the input 103. since the last digit of 103 is 3 and it is a global variable, so regardless of the input, it will always return the last digit of the global variable `num` which is 103. // =============> Write your prediction here -// 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 -// The last digit of 42 is 3 -// The last digit of 105 is 3 -// The last digit of 806 is 3 - // =============> write the output here -// The output is always '3' // Explain why the output is the way it is // =============> write your explanation here -// The output is always '3' because the function `getLastDigit` is using a global variable `num` which is set to 103 // 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 c25c70eb4..17b1cbde1 100644 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -15,15 +15,5 @@ // 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 - // calculate the height squared - const heightSquared = height * height; - // calculate the BMI - const BMI = weight / heightSquared; - // return the BMI to 1 decimal place - return BMI.toFixed(1); -} -let weight = 70; // in kg -let height = 1.73; // in meters - -console.log(`BMI is ${calculateBMI(weight, height)}`); + // return the BMI of someone based off their weight and height +} \ 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 a3e5f37f9..5b0ef77ad 100644 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -14,36 +14,3 @@ // 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) { - //split the string into an array of words - const wordsArray = string.split(" "); - // Convert each word to uppercase - const upperWordsArray = wordsArray.map((word) => word.toUpperCase()); - // Join the array back into a string with underscores - const toUpperSnakeCase = upperWordsArray.join("_"); - // Return the string in UPPER_SNAKE_CASE - return toUpperSnakeCase; -} -// Example usage for this function -// let string = "hello there"; - -// console.log(`The string in UPPER_SNAKE_CASE is: ${toUpperSnakeCase(string)}`); - -console.log( - `The string in UPPER_SNAKE_CASE for 'hello there' is: ${toUpperSnakeCase( - "hello there" - )}` -); - -console.log( - `The string in UPPER_SNAKE_CASE for 'lord of the rings' is: ${toUpperSnakeCase( - "lord of the rings" - )}` -); - -console.log( - `The string in UPPER_SNAKE_CASE for 'example usage for this function' is: ${toUpperSnakeCase( - "example usage for this function" - )}` -); diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js index 7f3ee9d2e..6265a1a70 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -4,32 +4,3 @@ // 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) { - // Remove the trailing "p" from the string - const penceStringWithoutTrailingP = penceString.substring( - 0, - penceString.length - 1 - ); - - // Ensure the number has at least 3 digits by padding from the left with zeros - const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); - - // Extract the pound portion - const pounds = paddedPenceNumberString.substring( - 0, - paddedPenceNumberString.length - 2 - ); - - // Extract the pence portion and pad right if needed - const pence = paddedPenceNumberString - .substring(paddedPenceNumberString.length - 2) - .padEnd(2, "0"); - - // Return the formatted result - return `£${pounds}.${pence}`; -} - -// Example usage: -console.log(toPounds("399p")); -console.log(toPounds("155p")); -console.log(toPounds("75p")); diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js index 1dcb19c4b..7c98eb0e8 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -11,7 +11,7 @@ function formatTimeDisplay(seconds) { return `${pad(totalHours)}:${pad(remainingMinutes)}:${pad(remainingSeconds)}`; } -// You will need to play computer with this example - use the Python Visualizer https://pythontutor.com/visualize.html#mode=edit +// 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 // Questions @@ -20,18 +20,15 @@ function formatTimeDisplay(seconds) { // =============> write your answer here // Call formatTimeDisplay with an input of 61, now answer the following: -// 3 times which is once each for hours, minutes, and seconds. + // b) What is the value assigned to num when pad is called for the first time? // =============> write your answer here -// 0, because pad is first called with totalHours, which is 0. + // c) What is the return value of pad is called for the first time? // =============> write your answer here -// '00' pad(0) becomes "0" → padded to "00" using padStart(2, "0"). + // 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, because the last call to pad is with remainingSeconds, which is 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", pad(1) becomes "1" → padded to "01" using padStart(2, "0"). - -// the final output of formatTimeDisplay(61) will be "00:01:01". diff --git a/Sprint-2/5-stretch-extend/format-time.js b/Sprint-2/5-stretch-extend/format-time.js index 7f223ccb5..32a32e66b 100644 --- a/Sprint-2/5-stretch-extend/format-time.js +++ b/Sprint-2/5-stretch-extend/format-time.js @@ -3,60 +3,23 @@ // 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 hours is less than 12, it should be am - const [hourStr, minute] = time.split(":"); - let hours = Number(hourStr); - let suffix = "am"; - // If hours is 0, it should be 12 am - if (hours === 0) { - hours = 12; + const hours = Number(time.slice(0, 2)); + if (hours > 12) { + return `${hours - 12}:00 pm`; } - // If hours is less than 12, it should be am - else if (hours === 12) { - suffix = "pm"; - } - // If hours is greater than 12, it should be pm - else if (hours > 12) { - hours -= 12; - suffix = "pm"; - } - //return `${time} am`; ignoring the actual minutes - const paddedHour = String(hours).padStart(2, "0"); - return `${paddedHour}:${minute} ${suffix}`; + return `${time} am`; } -// test 1 const currentOutput = formatAs12HourClock("08:00"); const targetOutput = "08:00 am"; console.assert( currentOutput === targetOutput, `current output: ${currentOutput}, target output: ${targetOutput}` ); -// test 2 + const currentOutput2 = formatAs12HourClock("23:00"); const targetOutput2 = "11:00 pm"; console.assert( currentOutput2 === targetOutput2, `current output: ${currentOutput2}, target output: ${targetOutput2}` ); -// test3 -const currentOutput3 = formatAs12HourClock("12:00"); -const targetOutput3 = "12:00 pm"; -console.assert( - currentOutput3 === targetOutput3, - `current output: ${currentOutput3}, target output: ${targetOutput3}` -); -//test 4 -const currentOutput4 = formatAs12HourClock("14:45"); -const targetOutput4 = "02:45 pm"; -console.assert( - currentOutput4 === targetOutput4, - `current output: ${currentOutput4}, target output: ${targetOutput4}` -); -// test 5 -const currentOutput5 = formatAs12HourClock("01:00"); -const targetOutput5 = "01:00 am"; -console.assert( - currentOutput5 === targetOutput5, - `current output: ${currentOutput5}, target output: ${targetOutput5}` -);