diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js index 117bcb2b6..01ba66b16 100644 --- a/Sprint-1/1-key-exercises/1-count.js +++ b/Sprint-1/1-key-exercises/1-count.js @@ -4,3 +4,6 @@ count = count + 1; // Line 1 is a variable declaration, creating the count variable with an initial value of 0 // Describe what line 3 is doing, in particular focus on what = is doing + +// We are updating the previous value of count to a new value. The = operator assigns a new value +// to the variable, meaning the data stored in memory is being changed. \ No newline at end of file diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js index 47561f617..db7d556f7 100644 --- a/Sprint-1/1-key-exercises/2-initials.js +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -5,7 +5,8 @@ let lastName = "Johnson"; // Declare a variable called initials that stores the first character of each string. // This should produce the string "CKJ", but you must not write the characters C, K, or J in the code of your solution. -let initials = ``; +let initials = `${firstName[0]}${middleName[0]}${lastName[0]}`; // https://www.google.com/search?q=get+first+character+of+string+mdn +console.log(initials); \ No newline at end of file diff --git a/Sprint-1/1-key-exercises/3-paths.js b/Sprint-1/1-key-exercises/3-paths.js index ab90ebb28..ce44994db 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -14,10 +14,17 @@ const lastSlashIndex = filePath.lastIndexOf("/"); const base = filePath.slice(lastSlashIndex + 1); console.log(`The base part of ${filePath} is ${base}`); + // Create a variable to store the dir part of the filePath variable +const dir = filePath.slice(0 ,lastSlashIndex + 1); +console.log(`The div part of ${filePath} is ${dir}`); + + // Create a variable to store the ext part of the variable +const lastDoteIndex = filePath.lastIndexOf("."); +const ext = filePath.slice(lastDoteIndex); +console.log(`The ext part of ${filePath} is ${ext}`); -const dir = ; -const ext = ; +// https://www.google.com/search?q=slice+mdn -// https://www.google.com/search?q=slice+mdn \ No newline at end of file +console.log(lastSlashIndex); \ No newline at end of file diff --git a/Sprint-1/1-key-exercises/4-random.js b/Sprint-1/1-key-exercises/4-random.js index 292f83aab..e869f726b 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -3,7 +3,22 @@ const maximum = 100; const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; +console.log(num); + // In this exercise, you will need to work out what num represents? // Try breaking down the expression and using documentation to explain what it means // It will help to think about the order in which expressions are evaluated // Try logging the value of num and running the program several times to build an idea of what the program is doing + + +// order of math calculation - () > ** > * / % > + - (Parentheses first, then Exponentiation +// (right to left), then Multiplication/Division/Modulo (left to right), then Addition/Subtraction +// (left to right)). + +//Math.floor - returns the value of x rounded down to its nearest integer +//Math.random - returns a random number + +// First, the innermost parentheses are evaluated: (maximum - minimum + 1). +// Then, the result is multiplied by the random number generated by the Math object. +// Math.floor rounds the result down to the nearest integer. +// Finally, the value is added to the minimum. \ No newline at end of file diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js index 653d6f5a0..e8eed5b42 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -1,5 +1,7 @@ // Predict and explain first... -// =============> write your prediction here +// =============> this function takes a string and capitalize the first letter of each word, +// then returns the modified string. However. if the first character is a space or a number, +// the function must validate this edge case before processing to avoid unexpected results. // call the function capitalise with a string input // interpret the error message and figure out why an error is occurring @@ -7,7 +9,16 @@ function capitalise(str) { let str = `${str[0].toUpperCase()}${str.slice(1)}`; return str; -} +}; -// =============> write your explanation here +console.log(capitalise("reza")); + +// =============> the parameter name and the variable are the same while causes this error // =============> write your new code here + +function capitalise(str) { + const cap_string = `${str[0].toUpperCase()}${str.slice(1)}`; + return cap_string; +}; + +console.log(capitalise("reza")); diff --git a/Sprint-2/1-key-errors/1.js b/Sprint-2/1-key-errors/1.js index f2d56151f..8b50336e3 100644 --- a/Sprint-2/1-key-errors/1.js +++ b/Sprint-2/1-key-errors/1.js @@ -1,7 +1,9 @@ // Predict and explain first... // Why will an error occur when this program runs? -// =============> write your prediction here +// =============> decimalNumber is already the name of the function parameter. +// You can't redeclare a variable with the same name in the same scope. and we do not even need to +// define a new variable // Try playing computer with the example to work out what is going on @@ -12,9 +14,19 @@ function convertToPercentage(decimalNumber) { return percentage; } -console.log(decimalNumber); +console.log(convertToPercentage(50)); + +// =============> i removed the variable -// =============> 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; +} + + +console.log(convertToPercentage(50)); \ No newline at end of file diff --git a/Sprint-2/1-key-errors/2.js b/Sprint-2/1-key-errors/2.js index aad57f7cf..2438dc3f8 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -3,18 +3,47 @@ // this function should square any number but instead we're going to get an error -// =============> write your prediction of the error here +// =============> the parameter can not be a number +// Valid JavaScript Identifiers +// Must start with a letter (a-z, A-Z), underscore (_), or dollar sign ($). +// Cannot start with a number (0-9). +// Can contain letters, numbers, underscores, or dollar signs after the first character. +// Cannot be a reserved keyword (e.g., if, else, function, return). -function square(3) { - return num * num; -} +// function square(3) { +// return num * num; +// } + +// console.log(square(4)); // =============> write the error message here +// /Users/setup/Documents/CYF/Module-Structuring-and-Testing-Data/Sprint-2/1-key-errors/2.js:13 +// function square(3) { +// ^ + +// SyntaxError: Unexpected number +// at wrapSafe (node:internal/modules/cjs/loader:1662:18) +// at Module._compile (node:internal/modules/cjs/loader:1704:20) +// at Object..js (node:internal/modules/cjs/loader:1895:10) +// at Module.load (node:internal/modules/cjs/loader:1465:32) +// at Function._load (node:internal/modules/cjs/loader:1282:12) +// at TracingChannel.traceSync (node:diagnostics_channel:322:14) +// at wrapModuleLoad (node:internal/modules/cjs/loader:235:24) +// at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5) +// at node:internal/main/run_main_module:36:49 + +// Node.js v22.16.0 // =============> explain this error message here +// First Two Lines: Locate the file path and the specific line of code causing the error. +// Following Lines: Display the type of error (SyntaxError) and its message. // Finally, correct the code to fix the problem // =============> write your new code here +function square(num) { + return num * num; +} +console.log(square(4)); diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js index b27511b41..9a0153bf2 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -1,6 +1,8 @@ // Predict and explain first... // =============> write your prediction here +// the console.log inside the function will run but the one in global will raise the undefine error +// we will get an undefine error because we are not retuning the value function multiply(a, b) { console.log(a * b); @@ -9,6 +11,13 @@ function multiply(a, b) { console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); // =============> write your explanation here +// To use the final result of a function, we must return the value. Otherwise, it will raise an undefined error. // Finally, correct the code to fix the problem // =============> write your new code here +function multiply(a, b) { + const result = a * b; + return result; +} + +console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); \ 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..5673a7e51 100644 --- a/Sprint-2/2-mandatory-debug/1.js +++ b/Sprint-2/2-mandatory-debug/1.js @@ -1,5 +1,7 @@ // Predict and explain first... // =============> write your prediction here +// Lines of code after a return statement are not executed, as the function exits immediately at that point + function sum(a, b) { return; @@ -9,5 +11,13 @@ function sum(a, b) { console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); // =============> write your explanation here +// we have to write the code inform of the return + // 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)}`); \ No newline at end of file diff --git a/Sprint-2/2-mandatory-debug/2.js b/Sprint-2/2-mandatory-debug/2.js index 57d3f5dc3..0f1503561 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -2,6 +2,8 @@ // Predict the output of the following code: // =============> Write your prediction here +// Since we haven't defined a parameter for the function, it won't use any arguments we pass to it. +// Instead, every time we call the function, it will use the num value in its calculation. const num = 103; @@ -15,10 +17,21 @@ console.log(`The last digit of 806 is ${getLastDigit(806)}`); // Now run the code and compare the output to your prediction // =============> write the output here -// Explain why the output is the way it is +// we get the same output for all the consol,log + // =============> write your explanation here +// we get the same output because the Function is not using the argument we send +// but instead is using the number in the variable num + // Finally, correct the code to fix the problem // =============> write your new code here - // This program should tell the user the last digit of each number. // Explain why getLastDigit is not working properly - correct the problem + +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)}`); \ No newline at end of file diff --git a/Sprint-2/3-mandatory-implement/1-bmi.js b/Sprint-2/3-mandatory-implement/1-bmi.js index 17b1cbde1..9951c6fab 100644 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -15,5 +15,9 @@ // 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 height_squared = height * height; + const bmi = height_squared / weight; + return bmi.toFixed(1); +} + +console.log(calculateBMI(83, 180)); diff --git a/Sprint-2/3-mandatory-implement/2-cases.js b/Sprint-2/3-mandatory-implement/2-cases.js index 5b0ef77ad..0c53f3694 100644 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -14,3 +14,12 @@ // 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 upper_snake_case(string) { + const replace_space = string.replaceAll(" ", "_"); + const to_uppercase = replace_space.toUpperCase(); + return to_uppercase; +} + +console.log(upper_snake_case("hello there")); +console.log(upper_snake_case("lord of the rings")); diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js index 6265a1a70..85c34859a 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -4,3 +4,29 @@ // 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) { + const penceStringWithoutTrailingP = penceString.substring( + 0, + penceString.length - 1 + ); + + const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); + const pounds = paddedPenceNumberString.substring( + 0, + paddedPenceNumberString.length - 2 + ); + + const pence = paddedPenceNumberString + .substring(paddedPenceNumberString.length - 2) + .padEnd(2, "0"); + + return `£${pounds}.${pence}`; +} + +// Test cases +console.log(toPounds("399p")); +console.log(toPounds("9p")); +console.log(toPounds("1234p")); // £12.34 (assuming input can be longer than 3 digits) +console.log(toPounds("0p")); +console.log(toPounds("5p")); \ No newline at end of file diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js index 7c98eb0e8..98d87f30a 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -17,18 +17,20 @@ function formatTimeDisplay(seconds) { // Questions // a) When formatTimeDisplay is called how many times will pad be called? -// =============> write your answer here +// =============> 3 // Call formatTimeDisplay with an input of 61, now answer the following: // b) What is the value assigned to num when pad is called for the first time? -// =============> write your answer here +// =============> 0 // c) What is the return value of pad is called for the first time? -// =============> write your answer here +// =============> "00" // d) What is the value assigned to num when pad is called for the last time in this program? Explain your answer -// =============> write your answer here +// =============> 1 +// Last pad call is pad(remainingSeconds), and remainingSeconds = 61 % 60 = 1 // e) What is the return value assigned to num when pad is called for the last time in this program? Explain your answer -// =============> write your answer here +// =============> "01" +// pad(1) => "01" because "1".padStart(2, "0") results in "01" diff --git a/Sprint-2/5-stretch-extend/format-time.js b/Sprint-2/5-stretch-extend/format-time.js index 32a32e66b..e16a19dbd 100644 --- a/Sprint-2/5-stretch-extend/format-time.js +++ b/Sprint-2/5-stretch-extend/format-time.js @@ -3,11 +3,18 @@ // Your task is to write tests for as many different groups of input data or edge cases as you can, and fix any bugs you find. function formatAs12HourClock(time) { - const hours = Number(time.slice(0, 2)); - if (hours > 12) { - return `${hours - 12}:00 pm`; + const [hourStr, minuteStr] = time.split(":"); + const hours = Number(hourStr); + + let period = hours >= 12 ? "pm" : "am"; + let displayHour = hours % 12; + if (displayHour === 0) { + displayHour = 12; // Handles 00:xx (midnight) and 12:xx (noon) } - return `${time} am`; + // If you input "08:00" is allowed to pass + const paddedHour = hourStr.length === 2 && displayHour < 10 ? `0${displayHour}` : `${displayHour}`; + + return `${paddedHour}:${minuteStr} ${period}`; } const currentOutput = formatAs12HourClock("08:00"); @@ -23,3 +30,10 @@ console.assert( currentOutput2 === targetOutput2, `current output: ${currentOutput2}, target output: ${targetOutput2}` ); + +console.assert(formatAs12HourClock("00:00") === "12:00 am", "Midnight failed"); +console.assert(formatAs12HourClock("01:00") === "01:00 am", "1am failed"); +console.assert(formatAs12HourClock("08:00") === "08:00 am", "8am failed"); +console.assert(formatAs12HourClock("12:00") === "12:00 pm", "Noon failed"); +console.assert(formatAs12HourClock("13:00") === "01:00 pm", "1pm failed"); +console.assert(formatAs12HourClock("23:00") === "11:00 pm", "11pm failed"); \ No newline at end of file