diff --git a/Sprint-2/1-key-exercises/1-count.js b/Sprint-2/1-key-exercises/1-count.js index 117bcb2b6..ba5f379ce 100644 --- a/Sprint-2/1-key-exercises/1-count.js +++ b/Sprint-2/1-key-exercises/1-count.js @@ -4,3 +4,8 @@ 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 + +/* +In line 3 the code is incrmenting the variable "count" by 1 , the operator "=" is assigning a new value to "count" by adding 1. + +*/ diff --git a/Sprint-2/1-key-exercises/2-initials.js b/Sprint-2/1-key-exercises/2-initials.js index 964c9563c..53b2ca1ce 100644 --- a/Sprint-2/1-key-exercises/2-initials.js +++ b/Sprint-2/1-key-exercises/2-initials.js @@ -5,6 +5,8 @@ const 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. -const initials = ``; +const initials = `${firstName.charAt(0)}${middleName.charAt(0)}${lastName.charAt(0)}`; // https://www.google.com/search?q=get+first+character+of+string+mdn + +console.log(initials); diff --git a/Sprint-2/1-key-exercises/3-paths.js b/Sprint-2/1-key-exercises/3-paths.js index ab90ebb28..1f97e42ea 100644 --- a/Sprint-2/1-key-exercises/3-paths.js +++ b/Sprint-2/1-key-exercises/3-paths.js @@ -17,7 +17,15 @@ 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, lastSlashIndex); +/*correction : slice(0,lastSlashIndex); is the correct method to extract the dir path + filePath.slice(start, end) => 0 represents the character 0 of the filePath String put 1 will skip the first charchter. + */ -// https://www.google.com/search?q=slice+mdn \ No newline at end of file +const ext = filePath.slice(filePath.lastIndexOf(".") + 1); + +// https://www.google.com/search?q=slice+mdn + +console.log(`The dir part of the filePath ${filePath}variable is ${dir}`); + +console.log(`The ext part of a variable file.txt is ${ext}`); diff --git a/Sprint-2/1-key-exercises/4-random.js b/Sprint-2/1-key-exercises/4-random.js index 292f83aab..ae3032815 100644 --- a/Sprint-2/1-key-exercises/4-random.js +++ b/Sprint-2/1-key-exercises/4-random.js @@ -7,3 +7,18 @@ const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; // 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 + +console.log(num); + +//First operation +//num is generating a random dicimal number with method Math.random() between 0 and 1 result eg :0.3948605 + +//Second operation +//The generated number is multiplied by the range+1 which is between 1-100 result eg 39.48605 + +//Third operation +//num is rounded down to the nearset whole number using the method Math.floor restult eg 39.48605 => 39 + +//Last operation is to add the "minimum" (in this case it's 1 or it can be changed to any changed number e.g 10) this will shift the random number so it starts counting from minimum, instead of from zero. +//eg . num was 39 => 40 +//num is a random whole number from 1 to 100. diff --git a/Sprint-2/2-mandatory-errors/0.js b/Sprint-2/2-mandatory-errors/0.js index cf6c5039f..e9c7b03f2 100644 --- a/Sprint-2/2-mandatory-errors/0.js +++ b/Sprint-2/2-mandatory-errors/0.js @@ -1,2 +1,2 @@ -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 +/*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?*/ diff --git a/Sprint-2/2-mandatory-errors/1.js b/Sprint-2/2-mandatory-errors/1.js index 7a43cbea7..ec5bd32c3 100644 --- a/Sprint-2/2-mandatory-errors/1.js +++ b/Sprint-2/2-mandatory-errors/1.js @@ -1,4 +1,11 @@ // trying to create an age variable and then reassign the value by 1 -const age = 33; +let age = 33; age = age + 1; + +/* +Answer : The Error is : TypeError: Assignment to constant variable. +Constants in JavaScript can't be reassigned to correct this we have to change the varible type from const => let. + +*/ +console.log(age); diff --git a/Sprint-2/2-mandatory-errors/2.js b/Sprint-2/2-mandatory-errors/2.js index e09b89831..a9c679e98 100644 --- a/Sprint-2/2-mandatory-errors/2.js +++ b/Sprint-2/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}`); +//Answer : the error was that CitOfBirth vaiable was declared after the method cosole .log() +//The solution is to declare it before calling it. + const cityOfBirth = "Bolton"; + +console.log(`I was born in ${cityOfBirth}`); diff --git a/Sprint-2/2-mandatory-errors/3.js b/Sprint-2/2-mandatory-errors/3.js index ec101884d..4420d21dd 100644 --- a/Sprint-2/2-mandatory-errors/3.js +++ b/Sprint-2/2-mandatory-errors/3.js @@ -1,5 +1,5 @@ const cardNumber = 4533787178994213; -const last4Digits = cardNumber.slice(-4); +const last4Digits = cardNumber.toString().slice(-4); // The last4Digits variable should store the last 4 digits of cardNumber // However, the code isn't working @@ -7,3 +7,15 @@ const last4Digits = cardNumber.slice(-4); // Then run the code and see what error it gives. // Consider: Why does it give this error? Is this what I predicted? If not, what's different? // Then try updating the expression last4Digits is assigned to, in order to get the correct value + +/* +Prediction : The slice method is used with String data type. here we have cardNumber varible with type Number. +Running the code will give a TypeError : cardNumber.slice is not a function +The solution is to convert numbe to string, There are three posibility: +String(cardNumber) +cardNumber.toString() +`${cardNumber}` + +*/ + +console.log(last4Digits); diff --git a/Sprint-2/2-mandatory-errors/4.js b/Sprint-2/2-mandatory-errors/4.js index 5f86c730b..149d812b5 100644 --- a/Sprint-2/2-mandatory-errors/4.js +++ b/Sprint-2/2-mandatory-errors/4.js @@ -1,2 +1,6 @@ -const 12HourClockTime = "8:53pm"; -const 24hourClockTime = "20:53"; +const HourClockTime12 = "8:53pm"; +const hourClockTime24 = "20:53"; + +/* +the naming of of the varibles is not correct varible should not start with a number +*/ diff --git a/Sprint-2/3-mandatory-interpret/1-percentage-change.js b/Sprint-2/3-mandatory-interpret/1-percentage-change.js index e24ecb8e1..6d139c41a 100644 --- a/Sprint-2/3-mandatory-interpret/1-percentage-change.js +++ b/Sprint-2/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; @@ -13,10 +13,52 @@ console.log(`The percentage change is ${percentageChange}`); // a) How many function calls are there in this file? Write down all the lines where a function call is made -// 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? +/* +Solution to a) + +There are 5 function calls in this file: +-------------|-----------------| --------| + 1 | Number() | line 4 | + 2 | replaceAll() | line 4 | + 3 | Number() | line 5 | + 4 | replaceAll() | line 5 | + 5 | console.log() | line 10 | +------------------------------------------ + +*/ + +// 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? +/* +Solution to b) + After running the code the terminal gives SyntaxError: missing ) after argument list BUT the actual error is not having a comma in line 5 in the replaceAll methode as it needs two arguments + eplaceAll("," "") => should be eplaceAll("," , "") +*/ // c) Identify all the lines that are variable reassignment statements +/* +Solution to c) +Variable reassignment statements lines are: + +line 4 : carPrice = Number(carPrice.replaceAll(",", "")); +line 5 : priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); +*/ // d) Identify all the lines that are variable declarations +/* + Solution to d) + Variable declarations lines are: + line 1 :let carPrice = "10,000"; + line 2 :let priceAfterOneYear = "8,543"; + line 7 :const priceDifference = carPrice - priceAfterOneYear; +c line 8 :const percentageChange = (priceDifference / carPrice) * 100; + +*/ // e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? + +/* +Solution to e) +The expresssion Number(carPrice.replaceAll(",","")) is removing the comma "," in CarPrice i.e from 10,000 to 10000 which is stored +in String type , removing the comma will insure the mathimatical operation will go normal when converted to type Number. + +*/ diff --git a/Sprint-2/3-mandatory-interpret/2-time-format.js b/Sprint-2/3-mandatory-interpret/2-time-format.js index 47d239558..2559beb56 100644 --- a/Sprint-2/3-mandatory-interpret/2-time-format.js +++ b/Sprint-2/3-mandatory-interpret/2-time-format.js @@ -1,4 +1,4 @@ -const movieLength = 8784; // length of movie in seconds +const movieLength = 90.5; // length of movie in seconds const remainingSeconds = movieLength % 60; const totalMinutes = (movieLength - remainingSeconds) / 60; @@ -12,14 +12,55 @@ 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? +/************************************************** */ +/* Solution a): There are 6 varibale declarations */ +/************************************************* */ // b) How many function calls are there? +/**************************************************/ +/* Solution b): */ +/* There is only one fuction call (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 +/*********************************************************************************************************************/ +/*Solution c): */ +/* The operator (%) called Modulo returns the remainder left over when one operand is divided by a second operand */ +/* In this expamle it gives the time remainder of the movie in seconds */ +/*********************************************************************************************************************/ + // d) Interpret line 4, what does the expression assigned to totalMinutes mean? +/****************************************************************************************************************************************************************************/ +/* Solution d): */ +/* The totalMinutes expression is calaculated first by subtrackting the lengh of movie by the reminder of seconds which rounds down the nearst minutes */ +/* Since we know the total number of seconds that are multiple of 60 we can can calculate the total number of minutes by dividing it over 60 since 1 minute is 60 seconds */ +/* This way we have the Movie total exact number of miutes. */ +/****************************************************************************************************************************************************************************/ + // e) What do you think the variable result represents? Can you think of a better name for this variable? +/*********************************************************************************************/ +/* Solution e): */ +/* The variable result represents the exact lenght of the movie in Hours + Minutes + Seconds */ +/* A better name for variable result could be : extctMovieLength */ +/*********************************************************************************************/ // f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer + +/***************************************************************************************************************************************************************/ +/* Solution e): */ +/* movieLength = 0 => exactMovieLength = 0:0:0 */ +/* movieLength = 60 => exactMovieLength = 0:1:0 */ +/* movieLength = 3676 => exactMovieLength = 1:1:16 */ +/* movieLength = -3600 => exactMoveLenght = -1:0:0 */ +/* movieLength = 90000 => exactMoveLenght = 25:0:0 */ +/* */ +/* This code Could be better: */ +/* - giving a negative value for movieLength will result in a negative clock: so there could have message that reject negative numbers. */ +/* - The program should have represented Hours/Min/Sec in this format 00:00:00 so each time should be represented with 2 digits. */ +/* - 25 hours exeeds 24 hours which represents a day so a variable total days could be added to represent time in days. */ +/* -Values with dicimal numbers will return the clock showing dicimal numbers this should be rounded up or down to the nearst time with an integer number */ +/* */ +/**********************************************************************************************************************************************************/ diff --git a/Sprint-2/3-mandatory-interpret/3-to-pounds.js b/Sprint-2/3-mandatory-interpret/3-to-pounds.js index 60c9ace69..4811b5193 100644 --- a/Sprint-2/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-2/3-mandatory-interpret/3-to-pounds.js @@ -2,14 +2,16 @@ const penceString = "399p"; const penceStringWithoutTrailingP = penceString.substring( 0, - penceString.length - 1 + penceString.length - 1, ); const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); + const pounds = paddedPenceNumberString.substring( 0, - paddedPenceNumberString.length - 2 + paddedPenceNumberString.length - 2, ); +console.log(pounds); const pence = paddedPenceNumberString .substring(paddedPenceNumberString.length - 2) @@ -25,3 +27,8 @@ console.log(`£${pounds}.${pence}`); // To begin, we can start with // 1. const penceString = "399p": initialises a string variable with the value "399p" +// 2. penceStringWithoutTrailingP = penceString.substring( 0, penceString.length - 1): This line of code slice the penceString varible by removing the "p" character from it. +// 3. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0") : This line of code adds "0" if lenght of penceStringWithoutTrailingP is less then 3 i.e e value is "1" => it will convert it to"001" or ifthe value is "22" it will convert it to "022". +// 4. const pounds = paddedPenceNumberString.substring( 0, paddedPenceNumberString.length - 2); : This line of code extract and store the value of pound from paddedPenceNumberString using the substring method since £1 = 100 pences => any number in the hudered position i.e third character from the right onwards has a value of £. +// 5. const pence = paddedPenceNumberString .substring(paddedPenceNumberString.length - 2) .padEnd(2, "0");: This line of code extract and store the value of pences paddedPenceNumberString using the substring method => instead of starting from the left it start from the right moving two positions then it adds "0"in case the pences value is less then 10. +// 6. console.log(`£${pounds}.${pence}`): This line of code prints the final result in £ and pences in nice readable way => £3.99 diff --git a/Sprint-2/4-stretch-explore/chrome.md b/Sprint-2/4-stretch-explore/chrome.md index 962580b82..ce193dcfe 100644 --- a/Sprint-2/4-stretch-explore/chrome.md +++ b/Sprint-2/4-stretch-explore/chrome.md @@ -8,8 +8,13 @@ Let's try an example. In the Chrome console, invoke the function `alert` with one argument, the string `"Hello world!"`; What effect does calling the `alert` function have? +Answer : it will brings a popup with alert message "Hello World" 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? What is the return value of `prompt`? + +Answer: calling the `prompt` function will bring up a dialog box with a field to put an answer + +The return value of `prompt is the variable `myName` diff --git a/Sprint-2/4-stretch-explore/objects.md b/Sprint-2/4-stretch-explore/objects.md index 0216dee56..2fbe33c46 100644 --- a/Sprint-2/4-stretch-explore/objects.md +++ b/Sprint-2/4-stretch-explore/objects.md @@ -5,12 +5,106 @@ In this activity, we'll explore some additional concepts that you'll encounter i Open the Chrome devtools Console, type in `console.log` and then hit enter What output do you get? +Answer : an object : log() { [native code] } Now enter just `console` in the Console, what output do you get back? +Answer : an object +console {debug: ƒ, error: ƒ, info: ƒ, log: ƒ, warn: ƒ, …} +assert +: +ƒ assert() +clear +: +ƒ clear() +context +: +ƒ context() +count +: +ƒ count() +countReset +: +ƒ countReset() +createTask +: +ƒ createTask() +debug +: +ƒ debug() +dir +: +ƒ dir() +dirxml +: +ƒ dirxml() +error +: +ƒ error() +group +: +ƒ group() +groupCollapsed +: +ƒ groupCollapsed() +groupEnd +: +ƒ groupEnd() +info +: +ƒ info() +log +: +ƒ log() +memory +: +MemoryInfo {totalJSHeapSize: 19300000, usedJSHeapSize: 18200000, jsHeapSizeLimit: 3760000000} +profile +: +ƒ profile() +profileEnd +: +ƒ profileEnd() +table +: +ƒ table() +time +: +ƒ time() +timeEnd +: +ƒ timeEnd() +timeLog +: +ƒ timeLog() +timeStamp +: +ƒ timeStamp() +trace +: +ƒ trace() +warn +: +ƒ warn() +Symbol(Symbol.toStringTag) +: +"console" +[[Prototype]] +: +Object Try also entering `typeof console` +Answer : object Answer the following questions: What does `console` store? +Answer : The console object does not permanently store data; instead, it provides an interface to record, display, and inspect temporary logs, warnings, and errors in the environment's debugging tool or terminal. What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? + +Answer : + +The console.log() is a method that accepts any value and outputs that the given value to the console + +The console.assert() is a static method that writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. + +The `.` is dot notation — it access the methods that belongs to the console object. such as log, assert, error .... ext diff --git a/Sprint-3/1-key-errors/0.js b/Sprint-3/1-key-errors/0.js index 653d6f5a0..5ee1f384f 100644 --- a/Sprint-3/1-key-errors/0.js +++ b/Sprint-3/1-key-errors/0.js @@ -1,5 +1,6 @@ // Predict and explain first... // =============> write your prediction here +// Tha parameter 'str' is declared another time insie the function , this will cause an error to be thrown. // call the function capitalise with a string input // interpret the error message and figure out why an error is occurring @@ -9,5 +10,10 @@ function capitalise(str) { return str; } -// =============> write your explanation here -// =============> write your new code here +// =============> write your explanation here SyntaxError: Identifier 'str' has already been declared => line 10 varibale str should not be declared again. +// =============> write your new code +// function capitalise(str) { +// str = `${str[0].toUpperCase()}${str.slice(1)}`; +// return str; +// } +// console.log(capitalise("hello world")); diff --git a/Sprint-3/1-key-errors/1.js b/Sprint-3/1-key-errors/1.js index f2d56151f..3149c37cf 100644 --- a/Sprint-3/1-key-errors/1.js +++ b/Sprint-3/1-key-errors/1.js @@ -2,19 +2,25 @@ // Why will an error occur when this program runs? // =============> write your prediction here +// The Program will throw an error because variable 'decimalNumber' is declared twice. // Try playing computer with the example to work out what is going on -function convertToPercentage(decimalNumber) { - const decimalNumber = 0.5; - const percentage = `${decimalNumber * 100}%`; +// function convertToPercentage(decimalNumber) { +// const decimalNumber = 0.5; +// const percentage = `${decimalNumber * 100}%`; - return percentage; -} +// return percentage; +// } -console.log(decimalNumber); - -// =============> write your explanation here +//console.log(decimalNumber); +// =============> write your explanation here : SyntaxError: Identifier 'decimalNumber' has already been declared => line 10 varibale decimalNumber should not be declared again. g // Finally, correct the code to fix the problem // =============> write your new code here +// function convertToPercentage(decimalNumber) { +// const percentage = `${decimalNumber * 100}%`; + +// return percentage; +// } +// console.log(convertToPercentage(0.5)); diff --git a/Sprint-3/1-key-errors/2.js b/Sprint-3/1-key-errors/2.js index aad57f7cf..64ca9e723 100644 --- a/Sprint-3/1-key-errors/2.js +++ b/Sprint-3/1-key-errors/2.js @@ -1,20 +1,21 @@ - // Predict and explain first BEFORE you run any code... // this function should square any number but instead we're going to get an error -// =============> write your prediction of the error here - +// =============> write your prediction of the error here : The funcation parameter 3 this will cause an error to be thrown because the parameter is not a valid identifier. function square(3) { return num * num; + } -// =============> write the error message here +// =============> write the error message here: SyntaxError: Unexpected number -// =============> explain this error message here +// =============> explain this error message here: SyntaxError: Unexpected number , the parameter 3 is not a valid identifier it should ba valid identifier like num. // Finally, correct the code to fix the problem // =============> write your new code here - - +// function square(num) { +// return num * num; +// } +// console.log(square(3)); diff --git a/Sprint-3/2-mandatory-debug/0.js b/Sprint-3/2-mandatory-debug/0.js index b27511b41..9b00d1e7e 100644 --- a/Sprint-3/2-mandatory-debug/0.js +++ b/Sprint-3/2-mandatory-debug/0.js @@ -1,14 +1,19 @@ // Predict and explain first... -// =============> write your prediction here +// =============> write your prediction here : The function multipy does not return any value so the result of calling the function will be unknown. -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 +// =============> write your explanation here : Calling the function has logged the result in the console but it has not returned the result ot the multiplicaion so the second console.log outside the function has no value to print and has printed undefined. // Finally, correct the code to fix the problem // =============> write your new code here +// function multiply(a, b) { +// return a * b; +// } + +// console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); diff --git a/Sprint-3/2-mandatory-debug/1.js b/Sprint-3/2-mandatory-debug/1.js index 37cedfbcf..ead98eb17 100644 --- a/Sprint-3/2-mandatory-debug/1.js +++ b/Sprint-3/2-mandatory-debug/1.js @@ -1,5 +1,5 @@ // Predict and explain first... -// =============> write your prediction here +// =============> write your prediction here: this code will give an error because the funcion does not return any value and calling it within the consle.log will print undefined. function sum(a, b) { return; @@ -8,6 +8,10 @@ function sum(a, b) { console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); -// =============> write your explanation here +// =============> write your explanation here : the sum a+b in line 6 should precede the return statement inorder to return the value. // Finally, correct the code to fix the problem // =============> write your new code here + +// function sum(a, b) { +// return a + b; +// } diff --git a/Sprint-3/2-mandatory-debug/2.js b/Sprint-3/2-mandatory-debug/2.js index 57d3f5dc3..d6acf02d9 100644 --- a/Sprint-3/2-mandatory-debug/2.js +++ b/Sprint-3/2-mandatory-debug/2.js @@ -1,7 +1,7 @@ // Predict and explain first... // Predict the output of the following code: -// =============> Write your prediction here +// =============> Write your prediction here: This code will throw an error because the function getLastDigit does not take any parameters but we are passing a parameter to it in the console.log statements. const num = 103; @@ -14,11 +14,22 @@ 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 +// =============> write the output here :output +/* The last digit of 42 is 3 + The last digit of 105 is 3 + The last digit of 806 is 3 +*/ // Explain why the output is the way it is -// =============> write your explanation here +// =============> write your explanation here: The funtion return on single value (3) no matter what parameter is passed to it because the function does not take any parameters and it is using the gobal variable num which is set to 103. So the last digit of 103 is always 3. // 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 +// Explain why getLastDigit is not working properly - correct the problem : The first declaration of num as constent should be removed and the function getLastDigit should take a parameter num to return the last digit of the number passed to it. diff --git a/Sprint-3/3-mandatory-implement/1-bmi.js b/Sprint-3/3-mandatory-implement/1-bmi.js index 58b1085f1..895086ce0 100644 --- a/Sprint-3/3-mandatory-implement/1-bmi.js +++ b/Sprint-3/3-mandatory-implement/1-bmi.js @@ -16,4 +16,7 @@ function calculateBMI(weight, height) { // return the BMI of someone based off their weight and height + return weight / (height * height); } + +console.log(calculateBMI(70, 1.73).toFixed(1)); // should return 23.4 diff --git a/Sprint-3/3-mandatory-implement/2-cases.js b/Sprint-3/3-mandatory-implement/2-cases.js index 5b0ef77ad..6382596b7 100644 --- a/Sprint-3/3-mandatory-implement/2-cases.js +++ b/Sprint-3/3-mandatory-implement/2-cases.js @@ -14,3 +14,7 @@ // 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(str) { + return str.toUpperCase().replaceAll(" ", "_"); +} +console.log(toUpperSnakeCase("lord of the rings")); diff --git a/Sprint-3/3-mandatory-implement/3-to-pounds.js b/Sprint-3/3-mandatory-implement/3-to-pounds.js index 10754da73..2d21f69b3 100644 --- a/Sprint-3/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-3/3-mandatory-implement/3-to-pounds.js @@ -4,3 +4,31 @@ // 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}`; +} + +console.log(toPounds("4798P")); +console.log(toPounds("31P")); +console.log(toPounds("0P")); +console.log(toPounds("-5576P")); +console.log(toPounds("4P")); +console.log(toPounds("832P")); +console.log(toPounds("200000P")); diff --git a/Sprint-3/4-mandatory-interpret/time-format.js b/Sprint-3/4-mandatory-interpret/time-format.js index c0dd9c9a5..0d6568d64 100644 --- a/Sprint-3/4-mandatory-interpret/time-format.js +++ b/Sprint-3/4-mandatory-interpret/time-format.js @@ -3,6 +3,7 @@ function pad(num) { while (numString.length < 2) { numString = "0" + numString; } + console.log(numString); return numString; } @@ -15,24 +16,26 @@ function formatTimeDisplay(seconds) { return `${pad(totalHours)}:${pad(remainingMinutes)}:${pad(remainingSeconds)}`; } +console.log(formatTimeDisplay(61)); + // 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 // a) When formatTimeDisplay is called how many times will pad be called? -// =============> write your answer here +// =============> write your answer here: ***Answer*** :Function pad 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 +// b) What is the value assigned to num when pad is called for the first time?: +// =============> write your answer here: ***Answer*** : The value assigned to num =61. // c) What is the return value of pad when it is called for the first time? -// =============> write your answer here +// =============> write your answer here: ***Answer*** :The value of pad when it is called for the first time is "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 +// 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: ***Answer***: The last call of pad in this program is pad(remainingSeconds) => remainingSeconds= (61%60=1) => num = 1. // e) What is the return value of pad when it is called for the last time in this program? Explain your answer -// =============> write your answer here +// =============> write your answer here : ***Answer*** : The value of pad when is called for the last time is the third part in `${pad(totalHours)}:${pad(remainingMinutes)}:${pad(remainingSeconds)}` => pad(remainingSeconds)=pad(1) since 1 has a length <2 return will be padded with 0 => pad (1)return "01". diff --git a/Sprint-3/5-stretch-extend/format-time.js b/Sprint-3/5-stretch-extend/format-time.js index 32a32e66b..7680eed4a 100644 --- a/Sprint-3/5-stretch-extend/format-time.js +++ b/Sprint-3/5-stretch-extend/format-time.js @@ -4,22 +4,91 @@ function formatAs12HourClock(time) { const hours = Number(time.slice(0, 2)); - if (hours > 12) { - return `${hours - 12}:00 pm`; + const minutes = Number(time.slice(3, 5)); + + if (hours < 12) { + return `${time} am`; + } else if (hours == 12) { + return `${time} am`; + } else if (hours == 24) { + return `12:00 am`; + } + + if (hours > 12 && hours < 22 && minutes < 10) { + return `${(hours - 12).toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")} pm`; + } + if (hours > 12 && hours < 22 && minutes >=10) { + return `${(hours - 12).toString().padStart(2, "0")}:${minutes} pm`; + } + if (hours >= 22 && minutes < 10) { + return `${hours - 12}:${minutes.toString().padStart(2, "0")} pm`; + } + if (hours >= 22 && minutes >= 10) { + return `${hours - 12}:${minutes} pm`; } - return `${time} am`; } -const currentOutput = formatAs12HourClock("08:00"); -const targetOutput = "08:00 am"; +const currentOutput = formatAs12HourClock("01:00"); +const targetOutput = "01:00 am"; console.assert( currentOutput === targetOutput, - `current output: ${currentOutput}, target output: ${targetOutput}` + `current output: ${currentOutput}, target output: ${targetOutput}`, ); const currentOutput2 = formatAs12HourClock("23:00"); const targetOutput2 = "11:00 pm"; console.assert( currentOutput2 === targetOutput2, - `current output: ${currentOutput2}, target output: ${targetOutput2}` + `current output: ${currentOutput2}, target output: ${targetOutput2}`, +); + +const currentOutput3 = formatAs12HourClock("00:00"); +const targetOutput3 = "00:00 am"; +console.assert( + currentOutput3 === targetOutput3, + `current output: ${currentOutput3}, target output: ${targetOutput3}`, +); + +const currentOutput4 = formatAs12HourClock("23:59"); // ***Asserrion failed : This needs fixing if hours > 12 minutes are not tracked and replaced by 00. =>fixec +// ); +const targetOutput4 = "11:59 pm"; +console.assert( + currentOutput4 === targetOutput4, + `current output: ${currentOutput4}, target output: ${targetOutput4}`, +); + +const currentOutput5 = formatAs12HourClock("12:00"); +const targetOutput5 = "12:00 am"; +console.assert( + currentOutput5 === targetOutput5, + `current output: ${currentOutput5}, target output: ${targetOutput5}`, // ***Asserrion failed : This needs fixing => fixed +); + +const currentOutput6 = formatAs12HourClock("24:00"); // ***Asserrion failed : This needs fixing =>fixed +const targetOutput6 = "12:00 am"; +console.assert( + currentOutput6 === targetOutput6, + `current output: ${currentOutput6}, target output: ${targetOutput6}`, +); + +const currentOutput7 = formatAs12HourClock("12:01"); // ***Asserrion failed : This needs fixing =>fixed +const targetOutput7 = "12:01 am"; +console.assert( + currentOutput7 === targetOutput7, + `current output: ${currentOutput7}, target output: ${targetOutput7}`, ); + +const currentOutput8 = formatAs12HourClock("22:10"); // ***Asserrion failed : This needs fixing =>fixed +const targetOutput8 = "01:10 am"; +console.assert( + currentOutput8=== targetOutput8, + `current output: ${currentOutput8}, target output: ${targetOutput8}`, +); + +const currentOutput9 = formatAs12HourClock("22:10"); // ***Asserrion failed : This needs fixing =>fixed +const targetOutput9 = "10:10 am"; +console.assert( + currentOutput9 === targetOutput9, + `current output: ${currentOutput9}, target output: ${targetOutput9}`, +); +