diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js index 117bcb2b6e..ec09d7fb85 100644 --- a/Sprint-1/1-key-exercises/1-count.js +++ b/Sprint-1/1-key-exercises/1-count.js @@ -4,3 +4,7 @@ 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 +// This line (line 3), is updating the value of the count variable. The = operator is an +// assignment operator which assigns the value on the right (count + 1) to the variable on the left (count). +// count = count + 1; This operation is called increment. +// An increment means increasing the value of a variable by 1. \ 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 47561f6175..ea5ed865f2 100644 --- a/Sprint-1/1-key-exercises/2-initials.js +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -4,8 +4,6 @@ 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 = firstName[0] + middleName[0] + lastName[0]; -let initials = ``; - -// https://www.google.com/search?q=get+first+character+of+string+mdn - +// https://www.google.com/search?q=get+first+character+of+string+mdn \ 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 ab90ebb28e..98ab371c3f 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -17,7 +17,7 @@ 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); +const ext = base.slice(base.lastIndexOf(".")); // https://www.google.com/search?q=slice+mdn \ 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 292f83aabb..59d1d93fd1 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -7,3 +7,16 @@ 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 + +// Math.random returns a random number between 0 (inclusive) and 1 (exclusive). +// const minimum = 1; const maximum = 100; +1 so, 100 - 1 + 1 = 100 +// Math.random() * 100 means the decimal number will be multiplied by 100, so the range of possible values is from 0 to 99.9999... +// Math.floor rounds the number down to the nearest whole number, so the possible values are from 0 to 99. +// Eg. 12.9 becomes 12, 0.3 becomes 0, 99.9 becomes 99. +// Brackets(), Multiply*, Function(Math.floor), Addition+ +// 1) Pick a random number between 0 and 1, eg. 0.5 +// 2) Multiply that number by 100, eg. 0.5 * 100 = 50 +// 3) Round that number down to the nearest whole number, eg. Math.floor(50) = 50 +// 4) Add 1 to that number, eg. 50 + 1 = 51 + +// num represents a random whole number between 1 and 100. \ 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 cf6c5039f7..9530ff0d72 100644 --- a/Sprint-1/2-mandatory-errors/0.js +++ b/Sprint-1/2-mandatory-errors/0.js @@ -1,2 +1,3 @@ -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? +// The forward slash is used to indicate a comment in JavaScript, so the computer will ignore these lines when running the program. diff --git a/Sprint-1/2-mandatory-errors/1.js b/Sprint-1/2-mandatory-errors/1.js index 7a43cbea76..4c570b531a 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; +let age = 33; age = age + 1; +console.log(age); + +// The code above will output 34, because we are reassigning the value of age +// to be the current value of age plus 1. So, 33 + 1 = 34. +// The error in the code is that it was trying to reassign a value to a variable +// that was declared with let. This is not allowed in JavaScript. \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/2.js b/Sprint-1/2-mandatory-errors/2.js index e09b89831d..88686319d1 100644 --- a/Sprint-1/2-mandatory-errors/2.js +++ b/Sprint-1/2-mandatory-errors/2.js @@ -1,5 +1,8 @@ // 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}`); + +// The error happens because cityOfBirth is used before it is defined. JavaScript runs +// code from top to bottom, so the variable must be declared first. \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/3.js b/Sprint-1/2-mandatory-errors/3.js index ec101884db..b5571ab658 100644 --- a/Sprint-1/2-mandatory-errors/3.js +++ b/Sprint-1/2-mandatory-errors/3.js @@ -1,5 +1,5 @@ -const cardNumber = 4533787178994213; -const last4Digits = cardNumber.slice(-4); +// const cardNumber = 4533787178994213; +// const last4Digits = cardNumber.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 code will not work because slice() is being used on cardNumber, which is a number. +// The slice() method only works on strings or arrays, not numbers. +// So I predict JavaScript will throw an error saying that slice is not a function for a number. + +const cardNumber = 4533787178994213; +const last4Digits = cardNumber.toString().slice(-4); +console.log(last4Digits); + +// After running the code, I got the output "4213", which is the last 4 digits of the card number. +// This is what i expected. +//testing \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/4.js b/Sprint-1/2-mandatory-errors/4.js index 21dad8c5d1..6605121098 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 12HourClockTime = "20:53"; +// const 24hourClockTime = "08:53"; + +// Variables cannot start with a number. +// When JavaScript tries to run the code, it throws a SyntaxError. +// To fix the error we can rename the variable to start with a letter, a +// underescore_ or a dollar sign $ instead of a number. + +const twelveHourClockTime = "8:53"; +const twentyFourHourClockTime = "08:53"; + +// I changed the time to match the 12 and 24 hr clock format. \ No newline at end of file diff --git a/Sprint-1/3-mandatory-interpret/1-percentage-change.js b/Sprint-1/3-mandatory-interpret/1-percentage-change.js index e24ecb8e18..5999a1e785 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; @@ -11,12 +11,49 @@ 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 +// a) How many function calls are there in this file? Write down all the +// lines where a function call is made + +// There are 5 function calls in this file. They are on lines 1, 2, 4, and 5. +// The functions being called are replaceAll() and Number(). +// Line 4: replaceAll and Number (2) +// Line 5: replaceAll and Number (2) +// Line 10: console.log (1) + + + +// 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? + +// The error is occuring on line 5. It is occuring because there is a missing +// comma between the replaceAll "". +// We can fix this by adding a comma between the two empty strings in the replaceAll +// function on line 5, like this: priceAfterOneYear = Number(priceAfterOneYear.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? // c) Identify all the lines that are variable reassignment statements +// carPrice = Number(carPrice.replaceAll(",", "")); +// priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); + + + // d) Identify all the lines that are variable declarations -// e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? +// Lines 1,2,7 and 8. +// let carPrice = "10,000"; +// let priceAfterOneYear = "8,543"; +// const priceDifference = carPrice - priceAfterOneYear; +// const percentageChange = (priceDifference / carPrice) * 100; + + + +// e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - +// what is the purpose of this expression? + +// carPrice.replaceAll(",", "") - Replaces all commas "," in the string with +// nothing "". e.g "10,000" becomes "10000". +// Number() - Converts the resulting string "10000" into the number 10000. +// The purpose of this is to take a string with commas (like "10,000") and turn +// it into a number (10000) that we can do math with. \ 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 47d2395587..d2d3793a44 100644 --- a/Sprint-1/3-mandatory-interpret/2-time-format.js +++ b/Sprint-1/3-mandatory-interpret/2-time-format.js @@ -1,25 +1,78 @@ -const movieLength = 8784; // length of movie in seconds +//const movieLength = 8784; // length of movie in seconds -const remainingSeconds = movieLength % 60; -const totalMinutes = (movieLength - remainingSeconds) / 60; +//const remainingSeconds = movieLength % 60; +//const totalMinutes = (movieLength - remainingSeconds) / 60; -const remainingMinutes = totalMinutes % 60; -const totalHours = (totalMinutes - remainingMinutes) / 60; +//const remainingMinutes = totalMinutes % 60; +//const totalHours = (totalMinutes - remainingMinutes) / 60; -const result = `${totalHours}:${remainingMinutes}:${remainingSeconds}`; -console.log(result); +//const result = `${totalHours}:${remainingMinutes}:${remainingSeconds}`; +//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? +// There are 6 variable declarations in this program. They are on lines 1, 3, 5, 7, +// 9 and 11. The variables being declared are movieLength, remainingSeconds, totalMinutes, +// remainingMinutes, totalHours and result. + + + // b) How many function calls are there? +// There is 1 function calls in this program. It is on lines 10. The functions is the +// 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 +// % is the remainder operator. +// movieLength % 60 - This gives the remainder when movieLength is divided by 60. +// Since there are 60 seconds in a minute, this tells us how many leftover seconds there are +// after counting full minutes. +// For example, 8784 % 60 = 24. So there are 24 seconds left after counting the minutes. + + + // d) Interpret line 4, what does the expression assigned to totalMinutes mean? +// movieLength - remainingSecond - This gives the total number of seconds in the movie after +// removing the leftover seconds. +// Divide by 60 - this converst the seconds into total full minutes. eg. (8784 - 24) = 8760, 8760 / 60 = 146. + + + // e) What do you think the variable result represents? Can you think of a better name for this variable? -// f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer +// The variable result is a string that represents the movie length in hours:minutes:seconds +// For example: 2:26:24 (2 hours, 26 minutes, 24 seconds) +// Better name can be movieDurationString. + + + +// f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? +// Explain your answer + +// This code will work for all positive integer values of movieLength. It will correctly calculate the hours, +// minutes and seconds for any length of movie. However, if movieLength is negative or not an integer, the +// code may not work as intended. For example, if movieLength is -100, the calculations will not make sense +// in the context of a movie length. If movieLength is a decimal, it may also cause issues with the calculations. + +const movieLength = 65; + +const remainingSeconds = movieLength % 60; +const totalMinutes = (movieLength - remainingSeconds) / 60; + +const remainingMinutes = totalMinutes % 60; +const totalHours = (totalMinutes - remainingMinutes) / 60; + +const formattedHours = String(totalHours).padStart(2, "0"); +const formattedMinutes = String(remainingMinutes).padStart(2, "0"); +const formattedSeconds = String(remainingSeconds).padStart(2, "0"); + +const movieDurationString = `${formattedHours}:${formattedMinutes}:${formattedSeconds}`; + +console.log(movieDurationString); // 00:01:05 diff --git a/Sprint-1/3-mandatory-interpret/3-to-pounds.js b/Sprint-1/3-mandatory-interpret/3-to-pounds.js index 60c9ace69a..fd2c67afa8 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -25,3 +25,18 @@ console.log(`£${pounds}.${pence}`); // To begin, we can start with // 1. const penceString = "399p": initialises a string variable with the value "399p" +// 2. const penceStringWithoutTrailingP = penceString.substring(0, penceString.length - 1): creates +// a new string variable that contains the original string without the last character (the "p"). +// 3. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"): creates a new +// string variable that pads the previous string with leading zeros until it is at least 3 characters +// long. eg. "45" becomes "045" and "7" becomes "007". +// 4. const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2): creates +// a new string variable that contains the first part of the padded string, which represents the pounds. +// It takes all characters except the last two. eg. "045" becomes "0" and "399" becomes "3". +// 5. const pence = paddedPenceNumberString.substring(paddedPenceNumberString.length - 2).padEnd(2, "0"): +// creates a new string variable that contains the last two characters of the padded string, which represents +// the pence. It also pads it with trailing zeros if necessary to ensure it is 2 characters long. eg. "045" +// becomes "45" and "7" becomes "70". +// 6. console.log(`£${pounds}.${pence}`): outputs the final price in pounds and pence format to the console. +// For example, if penceString is "399p", it will output "£3.99". If penceString is "45p", it will output "£0.45". +// If penceString is "7p", it will output "£0.07". diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js index 653d6f5a07..641b77bca5 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -1,13 +1,38 @@ // Predict and explain first... -// =============> write your prediction here +// I predict when this code runs, there will be a SyntaxError before the function executes. +// This is because the identifier 'str' has already been declared. // call the function capitalise with a string input +// capitalise("hello"); + + // interpret the error message and figure out why an error is occurring +// Uncaught SyntaxError: Unexpected identifier 'string' - this is the error message. +// This error is occuring because the variable 'str' is being redeclared within the +// function, which is not allowed in JavaScript. +// The duplicate use if 'str' is causing the syntax error. + + +//function capitalise(str) { + //let str = `${str[0].toUpperCase()}${str.slice(1)}`; + //return str; +//} + +// The issue is variable redeclaration. +// str is the function parameter. +// let str tries to create a new variable with the same name. +// JavaScript does not allow redeclaring a variable in the same scope. +// As a result, the code throws a SyntaxError when it encounters the second 'str' declaration. + +// New code without the error: +// 0.js — fully fixed version function capitalise(str) { - let str = `${str[0].toUpperCase()}${str.slice(1)}`; - return str; + if (!str) return str; // handles empty string + return str[0].toUpperCase() + str.slice(1); } -// =============> write your explanation here -// =============> write your new code here +// Test it +console.log(capitalise("hello")); // should print "Hello" +console.log(capitalise("world")); // should print "World" +console.log(capitalise("")); // should print "" diff --git a/Sprint-2/1-key-errors/1.js b/Sprint-2/1-key-errors/1.js index f2d56151f4..2f8e039ff0 100644 --- a/Sprint-2/1-key-errors/1.js +++ b/Sprint-2/1-key-errors/1.js @@ -1,20 +1,32 @@ // Predict and explain first... - // Why will an error occur when this program runs? -// =============> write your prediction here +// I predict an error will occur when this program runs because the variable 'decimalNumber' is already declared inside the function 'convertToPercentage' and cannot be redeclared. // Try playing computer with the example to work out what is going on +// When the 'function convertToPercentage(decimalNumber)' is created, +// Javascript already creates a variable called decimalNumber. then, inside the function, +// 'const decimalNumber = 0.5' tries to create another variable with the same name. This +// casues a syntax error because you cannot declare two variables with the same name in the same scope. -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); +// console.log(decimalNumber); -// =============> write your explanation here +// Write your explanation here +// I redelcared the parameter decimalNumber using const. +// I tried to log decimalNumber outside its scope. +// The variables declared inside the function are not available outside unless they are returned. // 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)); // "50%" diff --git a/Sprint-2/1-key-errors/2.js b/Sprint-2/1-key-errors/2.js index aad57f7cfe..4baed256e4 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -1,20 +1,28 @@ - // Predict and explain first BEFORE you run any code... +// 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 - -// =============> write your prediction of the error here +// Write your prediction of the error here: +// I predict that the error will be a syntax error because the parameter '3' is not a valid variable name. +// When you define a function,, the thing inside the parentahese must be a parameter name, NOT a number. -function square(3) { - return num * num; -} +// 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 the error messge here: +// When defining a function, inside the parentheses, you need to put a parameter name, which is a variable. +// In this case, '3' is not a valid parameter name because it is a number, not a variable. +// This causes a syntax error because Javascript expects a name, not a number. // Finally, correct the code to fix the problem +// Write your new code here -// =============> write your new code here - +function square(num) { + return num * num; +} +console.log(square(3)); // 9 +console.log(square(5)); // 25 diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js index b27511b417..3d0b813af8 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -1,14 +1,24 @@ -// Predict and explain first... +// Predict and explain first...write your prediction here +// I predict, when the code runs, it will print 320, but it will also print "The result of multiplying 10 and 32 is undefined". -// =============> write your prediction here +//function multiply(a, b) { +// console.log(a * b); +// } + +// console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); + +// Write your explanation here +// The function multiply(a, b) logs the result of a * b to the console but does not return a value. +// When multiply(10, 32) is called within the template literal, it logs 320 to the console but returns undefined. +// Therefore, inside the template literal, the value is undefined, which is why the final output +// becomes "The result of multiplying 10 and 32 is undefined". + +// Finally, correct the code to fix the problem +// Write your new code here +// To fix the problem, the function should return the result instead of logging it. function multiply(a, b) { - console.log(a * b); + return a * b; } console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); - -// =============> write your explanation here - -// 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 37cedfbcfd..c427fdf74e 100644 --- a/Sprint-2/2-mandatory-debug/1.js +++ b/Sprint-2/2-mandatory-debug/1.js @@ -1,13 +1,26 @@ -// Predict and explain first... -// =============> write your prediction here +// Predict and explain first...write your prediction here +// I think the code will return 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 +// When JavaScript sees the 'return' statement, it immediately stops the function. +// This is called terminating the function. +// It does NOT continue to the next line. +// So this part, 'a+b;' never runs. To return the sum of a and b, we need to put it +// on the same line as the return. +// Like the: 'return a + b;' -// =============> 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)}`); diff --git a/Sprint-2/2-mandatory-debug/2.js b/Sprint-2/2-mandatory-debug/2.js index 57d3f5dc35..793489ed85 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -1,24 +1,45 @@ // Predict and explain first... // Predict the output of the following code: -// =============> Write your prediction here +// Write your prediction here +// I think the output will be 'The last digit of 42 is 2', 'The last digit of 105 is 5', and 'The last digit of 806 is 6'. +// I think this will happen because the getLastDigit function is supposed to take a number, convert it to a string, and +// then return the last charecter of that string, which should be the last digit. -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)}`); + +// Now run the code and compare the output to your prediction +// Write the output here +// The output is: +// 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 +// The output is 3 for all numbers because the function getLastDigit is not taking any parameters. It always uses the +// global variable `num` which is set to 103. So it always returns the last digit of 103, which is 3. + +// Finally, correct the code to fix the problem +// Write your new code here + +function getLastDigit(number) { + return number.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)}`); -// Now run the code and compare the output to your prediction -// =============> write the output here -// Explain why the output is the way it is -// =============> write your explanation here -// 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 +// The function did not accept a parameter. It was a fixed variable (num = 103), so it always returned the last digit of 103. diff --git a/Sprint-2/3-mandatory-implement/1-bmi.js b/Sprint-2/3-mandatory-implement/1-bmi.js index 17b1cbde1b..c2b35cc719 100644 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -14,6 +14,30 @@ // Then when we call this function with the weight and height // It should return their Body Mass Index to 1 decimal place -function calculateBMI(weight, height) { +//function calculateBMI(weight, height) { // return the BMI of someone based off their weight and height -} \ No newline at end of file +// } + +// Notes: +// BMI = weight ÷ (height x height) +// eg. BMI = 70kg ÷ (1.73m x 1.73) +// BMI = 70kg ÷ 2.99 +// BMI = 23.41 +// BMI = 23.4 (to 1 decimal place) + +// I need to: +// 1. Square the height +// 2. Divide weight by squared height +// 3. Round the result to 1 decimal place +// 4. Return the result + +function calculateBMI(weight, height) { + const bmi = weight / (height * height); + return bmi.toFixed(1); +} + +console.log(calculateBMI(70, 1.73)); + + + +//toFixed(1) tells JavaScript to round the number to 1 decimal place. \ 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 5b0ef77ad9..154adbac0a 100644 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -14,3 +14,24 @@ // You will need to come up with an appropriate name for the function // Use the MDN string documentation to help you find a solution // This might help https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase + +// NOTES: +// "hello there" should become "HELLO_THERE" +// I need to turn all letters into CAPITALS and replace the space " " with underscore "-" + +// From the MDN documentation: +// I can use the toUpperCase() to turn the tring into all CAPS. +// I can use the replaceAll() to replace all the spaces with underscores. + +// Good function name: +// toUpperSnakeCase - this name is decriptive and indicates that the function will convert a string to upper snake case. + +function toUpperSnakeCase(str) { + return str.toUpperCase().replaceAll(" ", "_"); +} + +console.log(toUpperSnakeCase("hello there")); +// HELLO_THERE + +console.log(toUpperSnakeCase("lord of the rings")); +// LORD_OF_THE_RINGS \ No newline at end of file diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js index 6265a1a703..75f761c9df 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -1,6 +1,63 @@ // In Sprint-1, there is a program written in interpret/to-pounds.js +// ORIGINAL CODE: +//const penceString = "399p"; + +//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}`); + + // 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 +// You should call this function a number of times to check it works for different inputs. +// For example: +// toPounds("399p") should return "£3.99" +// toPounds("45p") should return "£0.45" +// toPounds("9p") should return "£0.09" +// toPounds("1200p") should return "£12.00" + +// The current code removes the "p", makes sur ethe number has at least 3 digits, splits pounds and +// pences and prints it in money format. +// Right now, it only works for "399p". I need it to work for "5p" and "1234p". +// I need to turn it into a function. eg. 'function toPounds(penceString)'. penceString clearly +// decribes what the input is. + +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("399p")); // £3.99 +console.log(toPounds("45p")); // £0.45 +console.log(toPounds("9p")); // £0.09 +console.log(toPounds("1200p")); // £12.00 \ 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 7c98eb0e8c..168c441a98 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -10,25 +10,37 @@ function formatTimeDisplay(seconds) { return `${pad(totalHours)}:${pad(remainingMinutes)}:${pad(remainingSeconds)}`; } +console.log(formatTimeDisplay(61)); +//testing +//console.log(formatTimeDisplay(3661)); // 01:01:01 +//console.log(formatTimeDisplay(45)); // 00:00:45 +//console.log(formatTimeDisplay(3600)); // 01:00:00 + + // 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 +// NOTES: +// This code converst seconds into HH:MM:SS and it uses pad() to make sure every number has 2 digits. e.g. 1 = "01". 0 = "00". +// + + // Questions // a) When formatTimeDisplay is called how many times will pad be called? -// =============> write your answer here +// pad will be called 3 times. pad(totalHours), pad(remainingMinutes) and pad(remainingSeconds). // 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 +// num = 0 // c) What is the return value of pad is called for the first time? -// =============> write your answer here +// Return value = 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 +// num = 1 because 61 seconds has 1 second remaining after removing 1 minute (60 seconds). // 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" because 1 is padded to 2 digits. diff --git a/Sprint-2/5-stretch-extend/format-time.js b/Sprint-2/5-stretch-extend/format-time.js index 32a32e66b8..10af29b351 100644 --- a/Sprint-2/5-stretch-extend/format-time.js +++ b/Sprint-2/5-stretch-extend/format-time.js @@ -2,24 +2,88 @@ // 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. +//function formatAs12HourClock(time) { + //const hours = Number(time.slice(0, 2)); + //if (hours > 12) { + //return `${hours - 12}:00 pm`; + //} + //return `${time} am`; +//} + +//const currentOutput = formatAs12HourClock("08:00"); +//const targetOutput = "08:00 am"; +//console.assert( + //currentOutput === 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}` +//); + +// Bug 1: Minutes are hardcoded for PM. It always uses :00 for PM. If the input is "23:45", the output becomes "11:00 pm". +// Bug 2: AM hours are notconverted to 12 hour format. It works for "8:00" but "00:30" becomes "00:30" when it should be "12:30 am". +// Bug 3: 12PM and 12AM are not handled correctly. "12:00" becomes "12:00 am" whjen it should be "12:00 pm", and "00:00" becomes "00:00 am" when it should be "12:00 am". + function formatAs12HourClock(time) { - const hours = Number(time.slice(0, 2)); - if (hours > 12) { - return `${hours - 12}:00 pm`; + let [hours, minutes] = time.split(":"); + hours = Number(hours); + let period = "am"; + + if (hours === 0) { + hours = 12; // midnight + } else if (hours === 12) { + period = "pm"; // noon + } else if (hours > 12) { + hours -= 12; + period = "pm"; } - return `${time} am`; + + const paddedHours = hours.toString().padStart(2, "0"); + + return `${paddedHours}:${minutes} ${period}`; } -const currentOutput = formatAs12HourClock("08:00"); -const targetOutput = "08:00 am"; -console.assert( - currentOutput === 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}` -); +//testing the function with various inputs. +//console.log(formatAs12HourClock("08:00")); // 08:00 am +//console.log(formatAs12HourClock("23:00")); // 11:00 pm +//console.log(formatAs12HourClock("00:30")); // 12:30 am +//console.log(formatAs12HourClock("12:15")); // 12:15 pm +//console.log(formatAs12HourClock("13:45")); // 01:45 pm +//console.log(formatAs12HourClock("11:59")); // 11:59 am +//console.log(formatAs12HourClock("12:00")); // 12:00 pm + +import { formatAs12HourClock } from "./formatAs12HourClock"; + +describe("formatAs12HourClock", () => { +test("formats morning time correctly", () => { +expect(formatAs12HourClock("08:00")).toBe("08:00 am"); +}); + +test("formats evening time correctly", () => { +expect(formatAs12HourClock("23:00")).toBe("11:00 pm"); +}); + +test("formats midnight correctly", () => { +expect(formatAs12HourClock("00:30")).toBe("12:30 am"); +}); + +test("formats noon correctly", () => { +expect(formatAs12HourClock("12:15")).toBe("12:15 pm"); +}); + +test("formats afternoon time correctly", () => { +expect(formatAs12HourClock("13:45")).toBe("01:45 pm"); +}); + +test("formats late morning correctly", () => { +expect(formatAs12HourClock("11:59")).toBe("11:59 am"); +}); + +test("formats exactly noon", () => { +expect(formatAs12HourClock("12:00")).toBe("12:00 pm"); +}); +}); \ No newline at end of file diff --git a/Sprint-3/1-implement-and-rewrite-tests/implement/1-get-angle-type.js b/Sprint-3/1-implement-and-rewrite-tests/implement/1-get-angle-type.js index 9e05a871e2..72c31b6900 100644 --- a/Sprint-3/1-implement-and-rewrite-tests/implement/1-get-angle-type.js +++ b/Sprint-3/1-implement-and-rewrite-tests/implement/1-get-angle-type.js @@ -1,37 +1,10 @@ -// Implement a function getAngleType -// -// When given an angle in degrees, it should return a string indicating the type of angle: -// - "Acute angle" for angles greater than 0° and less than 90° -// - "Right angle" for exactly 90° -// - "Obtuse angle" for angles greater than 90° and less than 180° -// - "Straight angle" for exactly 180° -// - "Reflex angle" for angles greater than 180° and less than 360° -// - "Invalid angle" for angles outside the valid range. - -// Assumption: The parameter is a valid number. (You do not need to handle non-numeric inputs.) - -// Acceptance criteria: -// After you have implemented the function, write tests to cover all the cases, and -// execute the code to ensure all tests pass. - function getAngleType(angle) { - // TODO: Implement this function + if (angle <= 0 || angle >= 360) return "Invalid angle"; + if (angle > 0 && angle < 90) return "Acute angle"; + if (angle === 90) return "Right angle"; + if (angle > 90 && angle < 180) return "Obtuse angle"; + if (angle === 180) return "Straight angle"; + if (angle > 180 && angle < 360) return "Reflex angle"; } -// The line below allows us to load the getAngleType function into tests in other files. -// This will be useful in the "rewrite tests with jest" step. module.exports = getAngleType; - -// This helper function is written to make our assertions easier to read. -// If the actual output matches the target output, the test will pass -function assertEquals(actualOutput, targetOutput) { - console.assert( - actualOutput === targetOutput, - `Expected ${actualOutput} to equal ${targetOutput}` - ); -} - -// TODO: Write tests to cover all cases, including boundary and invalid cases. -// Example: Identify Right Angles -const right = getAngleType(90); -assertEquals(right, "Right angle"); diff --git a/Sprint-3/1-implement-and-rewrite-tests/implement/2-is-proper-fraction.js b/Sprint-3/1-implement-and-rewrite-tests/implement/2-is-proper-fraction.js index 970cb9b641..7d009fced3 100644 --- a/Sprint-3/1-implement-and-rewrite-tests/implement/2-is-proper-fraction.js +++ b/Sprint-3/1-implement-and-rewrite-tests/implement/2-is-proper-fraction.js @@ -1,33 +1,6 @@ -// Implement a function isProperFraction, -// when given two numbers, a numerator and a denominator, it should return true if -// the given numbers form a proper fraction, and false otherwise. - -// Assumption: The parameters are valid numbers (not NaN or Infinity). - -// Note: If you are unfamiliar with proper fractions, please look up its mathematical definition. - -// Acceptance criteria: -// After you have implemented the function, write tests to cover all the cases, and -// execute the code to ensure all tests pass. - function isProperFraction(numerator, denominator) { - // TODO: Implement this function + if (denominator === 0) return false; + return numerator < denominator; } -// The line below allows us to load the isProperFraction function into tests in other files. -// This will be useful in the "rewrite tests with jest" step. module.exports = isProperFraction; - -// Here's our helper again -function assertEquals(actualOutput, targetOutput) { - console.assert( - actualOutput === targetOutput, - `Expected ${actualOutput} to equal ${targetOutput}` - ); -} - -// TODO: Write tests to cover all cases. -// What combinations of numerators and denominators should you test? - -// Example: 1/2 is a proper fraction -assertEquals(isProperFraction(1, 2), true); diff --git a/Sprint-3/1-implement-and-rewrite-tests/implement/3-get-card-value.js b/Sprint-3/1-implement-and-rewrite-tests/implement/3-get-card-value.js index c7559e787e..b2b41807b9 100644 --- a/Sprint-3/1-implement-and-rewrite-tests/implement/3-get-card-value.js +++ b/Sprint-3/1-implement-and-rewrite-tests/implement/3-get-card-value.js @@ -1,52 +1,16 @@ -// This problem involves playing cards: https://en.wikipedia.org/wiki/Standard_52-card_deck - -// Implement a function getCardValue, when given a string representing a playing card, -// should return the numerical value of the card. - -// A valid card string will contain a rank followed by the suit. -// The rank can be one of the following strings: -// "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" -// The suit can be one of the following emojis: -// "♠", "♥", "♦", "♣" -// For example: "A♠", "2♥", "10♥", "J♣", "Q♦", "K♦". - -// When the card is an ace ("A"), the function should return 11. -// When the card is a face card ("J", "Q", "K"), the function should return 10. -// When the card is a number card ("2" to "10"), the function should return its numeric value. - -// When the card string is invalid (not following the above format), the function should -// throw an error. - -// Acceptance criteria: -// After you have implemented the function, write tests to cover all the cases, and -// execute the code to ensure all tests pass. - function getCardValue(card) { - // TODO: Implement this function + const rank = card.slice(0, -1); // everything except the last char (suit) + const suit = card.slice(-1); // last char (suit) + const validSuits = ["♠","♥","♦","♣"]; + const validRanks = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]; + + if (!validRanks.includes(rank) || !validSuits.includes(suit)) { + throw new Error("Invalid card"); + } + + if (rank === "A") return 11; + if (["J","Q","K"].includes(rank)) return 10; + return Number(rank); } -// The line below allows us to load the getCardValue function into tests in other files. -// This will be useful in the "rewrite tests with jest" step. module.exports = getCardValue; - -// Helper functions to make our assertions easier to read. -function assertEquals(actualOutput, targetOutput) { - console.assert( - actualOutput === targetOutput, - `Expected ${actualOutput} to equal ${targetOutput}` - ); -} - -// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards. -// Examples: -assertEquals(getCardValue("9♠"), 9); - -// Handling invalid cards -try { - getCardValue("invalid"); - - // This line will not be reached if an error is thrown as expected - console.error("Error was not thrown for invalid card"); -} catch (e) {} - -// What other invalid card cases can you think of?