diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js index 117bcb2b6..6e091340f 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 + +// Line 3 is assigning (count + 1) to the variable count. +// In other word adding 1 to the variable count. \ 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..d33d79669 100644 --- a/Sprint-1/1-key-exercises/2-initials.js +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -5,7 +5,11 @@ 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.charAt(0)}${middleName.charAt(0)}${lastName.charAt(0)}`; +console.log(initials); +console.log(typeof initials); // https://www.google.com/search?q=get+first+character+of+string+mdn +// I used the mdn documentation to know how to get the first character of a string. +// I used charAt() method that takes the index of a string and return the character of it. diff --git a/Sprint-1/1-key-exercises/3-paths.js b/Sprint-1/1-key-exercises/3-paths.js index ab90ebb28..076f3322f 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -11,13 +11,18 @@ const filePath = "/Users/mitch/cyf/Module-JS1/week-1/interpret/file.txt"; const lastSlashIndex = filePath.lastIndexOf("/"); -const base = filePath.slice(lastSlashIndex + 1); +const base = filePath.slice(-8); console.log(`The base part of ${filePath} is ${base}`); // 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 = ; +const dir = filePath.slice(0, -8); +const ext = filePath.slice(filePath.length-3); -// https://www.google.com/search?q=slice+mdn \ No newline at end of file +console.log(`the dir part of filePath variable is ${dir}`); +console.log(ext); + +// https://www.google.com/search?q=slice+mdn + +// After studying the slice() method I was able to do this task easily. \ 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..f70a1aca6 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -2,8 +2,14 @@ const minimum = 1; 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 + +// num is a variable that will be assigned an integer number after the operators are done. +// Math.floor() rounds a decimal to its nearest number to make it an integer. ex = 1.2 => 1. +// Math.random() is a method used to create numbers between (0-1) and usually it creates a decimal like (0,2) or etc. +// each time I run it, I got different number as Math.random() generates different number each time we run it. \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/0.js b/Sprint-1/2-mandatory-errors/0.js index cf6c5039f..680eec82d 100644 --- a/Sprint-1/2-mandatory-errors/0.js +++ b/Sprint-1/2-mandatory-errors/0.js @@ -1,2 +1,8 @@ + This is just an instruction for the first activity - but it is just for human consumption -We don't want the computer to run these 2 lines - how can we solve this problem? \ No newline at end of file +We don't want the computer to run these 2 lines - how can we solve this problem? + +//solution: Simply comment the lines. +// 1- single line comment like: // example ... +// 2- multiline comment like : /* a, b, c */ +// comments are for instruction of guidance of who will read our codes, but the computer wont read them. \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/1.js b/Sprint-1/2-mandatory-errors/1.js index 7a43cbea7..9ca368df0 100644 --- a/Sprint-1/2-mandatory-errors/1.js +++ b/Sprint-1/2-mandatory-errors/1.js @@ -1,4 +1,10 @@ // trying to create an age variable and then reassign the value by 1 const age = 33; -age = age + 1; +//age = age + 1; + +// we can't do that with const variable, because JS locks the reference. +// the best choice is to use "let" variable. +let age2 = 33; +age2 = age2 + 1; // or age++ if wanna increase by "1"; +console.log(age2); diff --git a/Sprint-1/2-mandatory-errors/2.js b/Sprint-1/2-mandatory-errors/2.js index e09b89831..d851e72c3 100644 --- a/Sprint-1/2-mandatory-errors/2.js +++ b/Sprint-1/2-mandatory-errors/2.js @@ -1,5 +1,9 @@ // Currently trying to print the string "I was born in Bolton" but it isn't working... // what's the error ? -console.log(`I was born in ${cityOfBirth}`); const cityOfBirth = "Bolton"; +console.log(`I was born in ${cityOfBirth}`); + //const cityOfBirth = "Bolton"; + +// the problem is that our variable is not declared when we print it. +// to make it work, we should declare our "cityOfBirth" variable before we print it. diff --git a/Sprint-1/2-mandatory-errors/3.js b/Sprint-1/2-mandatory-errors/3.js index ec101884d..9f05fb1a3 100644 --- a/Sprint-1/2-mandatory-errors/3.js +++ b/Sprint-1/2-mandatory-errors/3.js @@ -1,5 +1,14 @@ const cardNumber = 4533787178994213; -const last4Digits = cardNumber.slice(-4); +//const last4Digits = cardNumber.slice(-4); +let str = cardNumber.toString().slice(-4); +const last4Digits = Number(str); +console.log(`${last4Digits} is the last 4 digits of ${cardNumber}`); + +//console.log(typeof last4Digits); + +// 1- the code is not working because 'slice()' method is not working with numbers. +// 2- it gives "type error" cardNumber.slice is not a function. +// 3- my prediction was correct as I studied the slice method and knew it. // The last4Digits variable should store the last 4 digits of cardNumber // However, the code isn't working diff --git a/Sprint-1/2-mandatory-errors/4.js b/Sprint-1/2-mandatory-errors/4.js index 21dad8c5d..34e30245c 100644 --- a/Sprint-1/2-mandatory-errors/4.js +++ b/Sprint-1/2-mandatory-errors/4.js @@ -1,2 +1,12 @@ +/* const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; \ No newline at end of file +const 24hourClockTime = "08:53"; +*/ +// As far as I know we can not start a variable name with a number in JS. +// Therefore these variables throw error. +// we can start the name of a variable with letters a-z, A-Z, _ ,and $ . +// This is how we correctly name our variables: +const twelveHourClockTime = "20:53"; +const twenty4HourClockTime = "08:53"; +console.log(`Twelve-hour clock: ${twelveHourClockTime}`); +console.log(`24-hour clock: ${twenty4HourClockTime}`); diff --git a/Sprint-1/3-mandatory-interpret/1-percentage-change.js b/Sprint-1/3-mandatory-interpret/1-percentage-change.js index e24ecb8e1..1e346b6db 100644 --- a/Sprint-1/3-mandatory-interpret/1-percentage-change.js +++ b/Sprint-1/3-mandatory-interpret/1-percentage-change.js @@ -2,7 +2,7 @@ let carPrice = "10,000"; let priceAfterOneYear = "8,543"; carPrice = Number(carPrice.replaceAll(",", "")); -priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); +priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); const priceDifference = carPrice - priceAfterOneYear; const percentageChange = (priceDifference / carPrice) * 100; @@ -12,11 +12,13 @@ console.log(`The percentage change is ${percentageChange}`); // 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 - + // line: 4 and line 5 and it is replaceAll(). // b) Run the code and identify the line where the error is coming from - why is this error occurring? How can you fix this problem? - + // error is coming from line 5. The error is because of not putting comma between the inputs of replaceAll function. + // To fix the problem just add a comma between the inputs of replaceAll function. // c) Identify all the lines that are variable reassignment statements - + // Line 4 and 5. // d) Identify all the lines that are variable declarations - + // we have variable declarations at lines 1, 2, 7 and 8. // e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? + // the purpose of that expression is to turn into number the string and replace all commas with an empty space. \ No newline at end of file diff --git a/Sprint-1/3-mandatory-interpret/2-time-format.js b/Sprint-1/3-mandatory-interpret/2-time-format.js index 47d239558..0cb4f84de 100644 --- a/Sprint-1/3-mandatory-interpret/2-time-format.js +++ b/Sprint-1/3-mandatory-interpret/2-time-format.js @@ -1,4 +1,4 @@ -const movieLength = 8784; // length of movie in seconds +const movieLength = 8724; // length of movie in seconds const remainingSeconds = movieLength % 60; const totalMinutes = (movieLength - remainingSeconds) / 60; @@ -12,14 +12,17 @@ console.log(result); // For the piece of code above, read the code and then answer the following questions // a) How many variable declarations are there in this program? - + // we have 6 variable declarations. // b) How many function calls are there? - + // here we have only one which is console.log(). // c) Using documentation, explain what the expression movieLength % 60 represents // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators - + // Remainder operator (%), returns the leftover when one operand divided by the other operand. + // movieLength % 60 expression represents the remaining seconds. // d) Interpret line 4, what does the expression assigned to totalMinutes mean? - + // that expression turns the seconds into minutes. // e) What do you think the variable result represents? Can you think of a better name for this variable? - + // the result variable represents the movie length in Hour, minutes and seconds. + // a better name can be "movieLength". // f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer + // as I changed the value of the movieLength the results has changed too.It means this code works with any value. \ No newline at end of file diff --git a/Sprint-1/3-mandatory-interpret/3-to-pounds.js b/Sprint-1/3-mandatory-interpret/3-to-pounds.js index 60c9ace69..ff190904e 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -1,21 +1,16 @@ const penceString = "399p"; -const penceStringWithoutTrailingP = penceString.substring( - 0, - penceString.length - 1 -); +const penceStringWithoutTrailingP = +penceString.substring(0, penceString.length - 1); // => "399"; -const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); -const pounds = paddedPenceNumberString.substring( - 0, - paddedPenceNumberString.length - 2 -); +const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); // => "399"; +const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2); // => "3" const pence = paddedPenceNumberString - .substring(paddedPenceNumberString.length - 2) - .padEnd(2, "0"); + .substring(paddedPenceNumberString.length - 2) // => "99" + .padEnd(2, "0"); -console.log(`£${pounds}.${pence}`); +console.log(`£${pounds}.${pence}`); // => "3.99" // This program takes a string representing a price in pence // The program then builds up a string representing the price in pounds @@ -24,4 +19,12 @@ console.log(`£${pounds}.${pence}`); // Try and describe the purpose / rationale behind each step // To begin, we can start with -// 1. const penceString = "399p": initialises a string variable with the value "399p" +// 1. const penceString = "399p": initializes a string variable with the value "399p" +// 2. const penceStringWithoutTrailingP uses the substring()method to remove the last character. +// 3. const paddedPenceNumberString tries to add "0" at the beginning, but the length is already 3; so it does nothing. +// Its worthy to talk about padStart() method. we use this to add a character at the beginning of a string. +// 4. const pound uses the substring() method on paddedPenceNumberString variable and remove its last two characters.Its value ll be "3". +// 5. const pence uses substring() on paddedPenceNumberString variable and take its length and then subtract it with 2 ... +// which will remain like this .substring(1), so it take the index 1 till the last which is only one more index that its character is 9 ... +// so the final value ll be "99". then uses padEnd( 2, "0") that can not add "0" at the end, as we set the length "2". +// 6. Lastly, we print the value of our pound and pence variable. which is "3.99". \ No newline at end of file diff --git a/Sprint-1/4-stretch-explore/chrome.md b/Sprint-1/4-stretch-explore/chrome.md index e7dd5feaf..fb7ab6868 100644 --- a/Sprint-1/4-stretch-explore/chrome.md +++ b/Sprint-1/4-stretch-explore/chrome.md @@ -12,7 +12,12 @@ invoke the function `alert` with an input string of `"Hello world!"`; What effect does calling the `alert` function have? +`answer` // there ll be a pop-up box showing a message and ask us to press ok in order to get rid of it. + Now try invoking the function `prompt` with a string input of `"What is your name?"` - store the return value of your call to `prompt` in an variable called `myName`. What effect does calling the `prompt` function have? +`answer` // Here we also have a pop-up box with an input, and it asks the user to type something. + What is the return value of `prompt`? +`answer` // if the user type something it returns `string` if the user cancel it then it return `null`. diff --git a/Sprint-1/4-stretch-explore/objects.md b/Sprint-1/4-stretch-explore/objects.md index 0216dee56..d5d99192d 100644 --- a/Sprint-1/4-stretch-explore/objects.md +++ b/Sprint-1/4-stretch-explore/objects.md @@ -13,4 +13,11 @@ Try also entering `typeof console` Answer the following questions: What does `console` store? + +`Answer` => console stores methods(function) that you can call to perform actions like logging, warning, or displaying error. + What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? + +`console.log()` prints the out put. +`console.assert()` checks the condition. +`The dot operator` is called member access. It accesses a property or method of an object. \ 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..9272d7011 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -1,13 +1,25 @@ // Predict and explain first... -// =============> write your prediction here +// =============> write your prediction here + // `My prediction` => The capitalise function tries to capitalize the first character of the string and concat it with the rest. This function may not run as it has error. // call the function capitalise with a string input + // `I called the capitalise function and found out there is a syntax error, we have already declared our 'str' variable in our function parameter, so its not a good idea to declare the same variable name as it ll throw an error.` + // interpret the error message and figure out why an error is occurring + // `The error occurs because we have declared the same (str) variable two times`. We can not declare two variables with the same name. -function capitalise(str) { +/*function capitalise(str) { let str = `${str[0].toUpperCase()}${str.slice(1)}`; return str; } +console.log(capitalise("Roman"));*/ // =============> write your explanation here + // `to make this function run we should make we should declare two different variables in our function + // .one as a parameter of the func and assign it with the above value. the second option is to return directly without creating a variable.` // =============> write your new code here +function capitalized(str2){ + let capitalizedStr = `${str2[0].toUpperCase()}${str2.slice(1)}`; + return capitalizedStr; +} +console.log(capitalized("hi dear")); \ 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..95e0b8dd5 100644 --- a/Sprint-2/1-key-errors/1.js +++ b/Sprint-2/1-key-errors/1.js @@ -1,20 +1,26 @@ // Predict and explain first... +// =====> This function tries to convert a decimal number to percentage, but I think it will not run as we have declared same variable name two times. // Why will an error occur when this program runs? -// =============> write your prediction here +// =============> It will throw an error as we have declared decimalNumber variable in our function parameter and again we declared this decimalNumber variable inside our function. // Try playing computer with the example to work out what is going on -function convertToPercentage(decimalNumber) { +/*function convertToPercentage(decimalNumber) { const decimalNumber = 0.5; const percentage = `${decimalNumber * 100}%`; return percentage; } +console.log(decimalNumber);*/ -console.log(decimalNumber); - -// =============> write your explanation here +// =============> I tried to run this, it throw an error like: 'decimalNumber' has already been declared. to fix this we should remove the decimalNumber variable which we have inside our function. // Finally, correct the code to fix the problem // =============> write your new code here +function convertToPercentage(decimalNumber) { + const percentage = `${decimalNumber * 100}%`; + console.log(`Your Decimal number will be ${percentage}.`); + return percentage; +} +convertToPercentage(0.9); \ 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..d5e6996ac 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -1,20 +1,27 @@ // Predict and explain first BEFORE you run any code... +// ====> As my understanding this function will throw and error as we have have not called the function with the argument 'num' . -// this function should square any number but instead we're going to get an error +// this function should square any number but instead we're going to get an error. +// ====> it will not square any number but 3 when we call it with the argument 'num' inside. -// =============> write your prediction of the error here -function square(3) { +/*function square(3) { return num * num; -} +}*/ // =============> write the error message here +// the error message is: SyntaxError: Unexpected number. // =============> explain this error message here +// after running I understood that we can not put a value in function parameter but a variable name. to make it short, in JavaScript we put variable in parameter and value as argument when calling the function. // Finally, correct the code to fix the problem // =============> write your new code here +function square(num) { + return num * num; +} +console.log(square(9)); diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js index b27511b41..824343ce1 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -1,14 +1,20 @@ // Predict and explain first... -// =============> write your prediction here +// =============> This function will not execute any operation, as it does not return anything. -function multiply(a, b) { - console.log(a * b); -} +// function multiply(a, b) { +// console.log(a * b); +// } -console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); +// console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); // =============> write your explanation here +// After running the code, I found that the function works partially, it prints lines 6 and as we called the function on line 9. but line 9 has an error to be fixed. As it does not print what we need. +// also : In JavaScript, if a function doesn’t explicitly return something, it automatically returns. this is why we have got the first input ok and the second input Undefined. // Finally, correct the code to fix the problem -// =============> write your new code here +// =============> write your new code here; +function multiply(a, b) { + return (a * b); +} +console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); diff --git a/Sprint-2/2-mandatory-debug/1.js b/Sprint-2/2-mandatory-debug/1.js index 37cedfbcf..21ff0fcbb 100644 --- a/Sprint-2/2-mandatory-debug/1.js +++ b/Sprint-2/2-mandatory-debug/1.js @@ -1,13 +1,17 @@ // Predict and explain first... -// =============> write your prediction here +// =============> This function will not return the sum of a + b as the operation is located on the next line or return. so we ll have a syntax error. -function sum(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)}`); +// =============> after running the code I got undefined on the output as our function does not return anything. because after return keyword our function do not operate the codes. -// =============> write your explanation here // Finally, correct the code to fix the problem // =============> write your new code here +function sum(a, b) { + return a + b; +} +console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); \ 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..3e5a5e12b 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -1,24 +1,34 @@ // Predict and explain first... // Predict the output of the following code: -// =============> Write your prediction here +// =============> In my knowledge only the output from line 6 will be printed correctly. As for line 12, 13, and 14 it will throw error or will print undefined as we don't declare any variable for them but only value. -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 -// =============> write the output here +// =============> the output after running the code is: ---The last digit of 42 is 3 --- The last digit of 105 is 3 --- The last digit of 806 is 3; +// my prediction was half correct as it worked only with line 6 but it did not throw error or undefined. here not syntax error but logical error. + // Explain why the output is the way it is -// =============> write your explanation here +// =============> Its because JavaScript only calls the function 3 times, it does not read or ignore the value inside as they are not declared. + // 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 +// ===> it was not working with line 12, 13, and 14 because we had not declared the variable inside the function parameter, to fix the issue is to declare the num variable inside the parameter of the function. and remove the const variable of num above the function or line 6. diff --git a/Sprint-2/3-mandatory-implement/1-bmi.js b/Sprint-2/3-mandatory-implement/1-bmi.js index 17b1cbde1..c8ea9d011 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 + let heightSquare = height * height; + let bmi = weight / heightSquare; + console.log(`Your BMI is ${bmi.toFixed(1)}`) + return bmi; +} +calculateBMI(65, 1.73); // ==> 21.7 diff --git a/Sprint-2/3-mandatory-implement/2-cases.js b/Sprint-2/3-mandatory-implement/2-cases.js index 5b0ef77ad..43ae195d6 100644 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -10,6 +10,12 @@ // it returns the string in UPPER_SNAKE_CASE, so "HELLO_THERE" // Another example: "lord of the rings" should be "LORD_OF_THE_RINGS" +function upperSnakeCase(str){ +let snakeCase = str.replaceAll(" ", "_").toUpperCase(); +console.log(snakeCase); +return snakeCase; +} +upperSnakeCase("the vampire dairies"); // "THE_VAMPIRE_DAIRIES" // You will need to come up with an appropriate name for the function // Use the MDN string documentation to help you find a solution diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js index 6265a1a70..5001add24 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -2,5 +2,20 @@ // You will need to take this code and turn it into a reusable block of code. // You will need to declare a function called toPounds with an appropriately named parameter. - // You should call this function a number of times to check it works for different inputs +function toPounds(penceString) { + 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"); + +console.log(`£${pounds}.${pence}`); +} +toPounds("399p"); // ===> £3.99 +toPounds("488p"); // ===> £4.88 +toPounds("999p"); // ===> £9.99 diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js index 7c98eb0e8..2e586fbf9 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -1,3 +1,4 @@ + function pad(num) { return num.toString().padStart(2, "0"); } @@ -7,9 +8,10 @@ function formatTimeDisplay(seconds) { const totalMinutes = (seconds - remainingSeconds) / 60; const remainingMinutes = totalMinutes % 60; const totalHours = (totalMinutes - remainingMinutes) / 60; - + console.log(`${pad(totalHours)}:${pad(remainingMinutes)}:${pad(remainingSeconds)}`); return `${pad(totalHours)}:${pad(remainingMinutes)}:${pad(remainingSeconds)}`; } +formatTimeDisplay(61); // ===> 00:01:01 // 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 @@ -17,18 +19,18 @@ function formatTimeDisplay(seconds) { // Questions // a) When formatTimeDisplay is called how many times will pad be called? -// =============> write your answer here +// =============> pad function will be called `3` times. // 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 +// =============> the num value is '0' when pad is called for the first time. // c) What is the return value of pad is called for the first time? -// =============> write your answer here +// =============> the return value of num is '00' when pad is called for the first time. // 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 value of num is '1' when pad is called for the last time. to add more remainingSeconds = 61 % 60 = 1. this is why we have 1 for num value. // 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 return value of num is '01' when pad is called last time. in short, remainingSeconds = 61 % 60 = 1 as num equals 1 then we have 0 from padStart(2, "0"); so the result will be "01". \ No newline at end of file diff --git a/Sprint-2/5-stretch-extend/format-time.js b/Sprint-2/5-stretch-extend/format-time.js index 32a32e66b..cb69b5878 100644 --- a/Sprint-2/5-stretch-extend/format-time.js +++ b/Sprint-2/5-stretch-extend/format-time.js @@ -1,13 +1,32 @@ // This is the latest solution to the problem from the prep. // Make sure to do the prep before you do the coursework // Your task is to write tests for as many different groups of input data or edge cases as you can, and fix any bugs you find. +// --- > Debugging this code was not easy for me, I could solve this by the help of AI Explaining each step and conditions and finally we made it work well with different inputs, I mean string with number character. function formatAs12HourClock(time) { const hours = Number(time.slice(0, 2)); - if (hours > 12) { - return `${hours - 12}:00 pm`; + const minutes = time.slice(2); + + let formattedHours; + + if (hours === 0) { + formattedHours = 12; + } else if (hours > 12) { + formattedHours = hours - 12; + } else { + formattedHours = hours; + } + + // ---> Add leading zero if needed + if (formattedHours < 10) { + formattedHours = "0" + formattedHours; + } + + if (hours >= 12) { + return `${formattedHours}${minutes} pm`; + } else { + return `${formattedHours}${minutes} am`; } - return `${time} am`; } const currentOutput = formatAs12HourClock("08:00"); @@ -23,3 +42,8 @@ console.assert( currentOutput2 === targetOutput2, `current output: ${currentOutput2}, target output: ${targetOutput2}` ); +console.assert(formatAs12HourClock("00:00") === "12:00 am"); +console.assert(formatAs12HourClock("12:00") === "12:00 pm"); +console.assert(formatAs12HourClock("13:05") === "01:05 pm"); +console.assert(formatAs12HourClock("01:05") === "01:05 am"); +console.assert(formatAs12HourClock("23:59") === "11:59 pm");