diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 2dd5a2432..4cc21d644 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -8,4 +8,4 @@ "vsliveshare.vsliveshare", "Orta.vscode-jest" ] -} +} \ No newline at end of file diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js index 117bcb2b6..d0a20ff3b 100644 --- a/Sprint-1/1-key-exercises/1-count.js +++ b/Sprint-1/1-key-exercises/1-count.js @@ -3,4 +3,9 @@ let count = 0; 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 +// Describe what line 3 is doing, in particular focus on what = is doing + +// Line 3 is updating the value of the count variable by adding 1 to its current value. The = operator is used for assignment, meaning it takes the value on the right (count + 1) and assigns it to the variable on the left (count). +// The expression count + 1 calculates the new value, and then the = operator assigns this new value back to the count variable. +// The count variable now holds the value 1, which is the result of the initial value (0) plus 1. +// count++; diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js index 47561f617..041fe9c80 100644 --- a/Sprint-1/1-key-exercises/2-initials.js +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -6,6 +6,12 @@ let lastName = "Johnson"; // 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 = ``; +initials = firstName[0] + middleName[0] + lastName[0]; +// The above code uses the bracket notation to access the first character of each string. +console.log(initials); // Output: CKJ +// The code above uses the bracket notation to access the first character of each string. +// The firstName[0] accesses the first character of the firstName string, which is "C". + // https://www.google.com/search?q=get+first+character+of+string+mdn diff --git a/Sprint-1/1-key-exercises/3-paths.js b/Sprint-1/1-key-exercises/3-paths.js index ab90ebb28..8039a73c5 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -17,7 +17,11 @@ 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 lastDotIndex = base.lastIndexOf("."); +const ext = base.slice(lastDotIndex + 1); + +console.log(`The dir part is ${dir}`); +console.log(`The ext part is ${ext}`); // 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 292f83aab..53528aa8b 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -7,3 +7,17 @@ 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(`The random number is ${num}`); +// The variable num represents a random integer between the values of minimum (1) and maximum (100), inclusive. +// The expression Math.random() generates a random floating-point number between 0 (inclusive) and 1 (exclusive). +// The expression (maximum - minimum + 1) calculates the range of possible values (100 - 1 + 1 = 100). +// Multiplying Math.random() by this range scales the random number to the desired range. +// Adding minimum shifts the range to start at the minimum value (1). +// Finally, Math.floor() rounds down the result to the nearest whole number, ensuring that num is an integer. +// Therefore, num will always be a whole number between 1 and 100, inclusive. +// This means that every time the program is run, it will produce a different random number within this range. +// The program logs the value of num to the console, showing the generated random number each time it is executed. +// This is useful for scenarios where you need a random number, such as in games, simulations, or testing. +// The use of Math.random(), Math.floor(), and the arithmetic operations ensures that the random number is uniformly distributed across the specified range. +// The program can be run multiple times to see different random numbers generated each time, demonstrating the randomness of the output. diff --git a/Sprint-1/1-key-exercises/test.js b/Sprint-1/1-key-exercises/test.js new file mode 100644 index 000000000..69f55f513 --- /dev/null +++ b/Sprint-1/1-key-exercises/test.js @@ -0,0 +1,18 @@ +function checkTime(time){ + + return time.slice(0,1)+time.slice(1,2) +} + +console.log(checkTime("12:34")); // Output: 12 +console.log(checkTime("23:59")); // Output: 23 + +num1 = checkTime("13:34"); + +if (num1 > 12 && num1 < 24) { + + console.log("PM"); + +} else +{ + console.log("AM"); +} \ 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..e6b744a05 100644 --- a/Sprint-1/2-mandatory-errors/0.js +++ b/Sprint-1/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-1/2-mandatory-errors/1.js b/Sprint-1/2-mandatory-errors/1.js index 7a43cbea7..469a01a54 100644 --- a/Sprint-1/2-mandatory-errors/1.js +++ b/Sprint-1/2-mandatory-errors/1.js @@ -1,4 +1,12 @@ // trying to create an age variable and then reassign the value by 1 -const age = 33; -age = age + 1; +let age = 33; +age = age + 1; +// The above code will throw an error because 'age' is a constant variable declared with 'const'. +// In JavaScript, variables declared with 'const' cannot be reassigned a new value after their initial assignment. +// To fix this, you can declare 'age' using 'let' instead of 'const', allowing it to be reassigned. +// let age = 33; +console.log(age); // Output: 34 +// The code above declares a variable 'age' with an initial value of 33. +// Then, it reassigns the value of 'age' by adding 1 to its current value. +// The final value of 'age' will be 34, which is the result of the initial value (33) plus 1. \ 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 e09b89831..029316596 100644 --- a/Sprint-1/2-mandatory-errors/2.js +++ b/Sprint-1/2-mandatory-errors/2.js @@ -1,5 +1,12 @@ // 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}`); +//console.log(`I was born in ${cityOfBirth}`); +//const cityOfBirth = "Bolton"; + +// The error occurs because the variable 'cityOfBirth' is being used before it has been declared. +// To fix this, you should declare the variable 'cityOfBirth' before using it in the console.log statement. +// Here's the corrected code: const cityOfBirth = "Bolton"; +console.log(`I was born in ${cityOfBirth}`); +// Now, the code will correctly print "I was born in Bolton" without any errors. \ 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 ec101884d..445a18c1a 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 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 the `slice` method is being called on a number (cardNumber), which does not have a `slice` method. The `slice` method is typically used with strings or arrays, not numbers. +// Running the code will likely result in a TypeError indicating that `slice` is not a function or is not defined for the number type. +// Running the code confirms the prediction, as it throws an error: "TypeError: cardNumber.slice is not a function". +// To fix this, we need to convert the cardNumber to a string before using the `slice` method. +const last4Digits = String(cardNumber).slice(-4); +// Now, last4Digits will correctly store the last 4 digits of cardNumber. +console.log(`The last 4 digits of the card number are: ${last4Digits}`); +// This will output: "The last 4 digits of the card number are: 4213" + +// The code now works correctly, and the last4Digits variable contains the last four digits of the card number as a string. +// The final output will be "The last 4 digits of the card number are: 4213". \ 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 21dad8c5d..f0ab94e12 100644 --- a/Sprint-1/2-mandatory-errors/4.js +++ b/Sprint-1/2-mandatory-errors/4.js @@ -1,2 +1,2 @@ -const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; \ No newline at end of file +const twelveHourClockTime = "20:53"; +const twentyFourHourClockTime = "08:53"; \ 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 e24ecb8e1..ed89eb6be 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; @@ -20,3 +20,27 @@ console.log(`The percentage change is ${percentageChange}`); // 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? + + +// a) There are 3 function calls in this file: +// 1. `carPrice.replaceAll(",", "")` on line 4 +// 2. `priceAfterOneYear.replaceAll(",", "")` on line 5 +// 3. `console.log(...)` on line 9 + + +// b) The error occurs on line 5 because there is a syntax error in the `replaceAll` method call. +// The correct syntax should be `replaceAll(",", "")` instead of `replaceAll("," "")`. +// To fix this, you need to add a comma between the two arguments. + +// c) The variable reassignment statements are: +// 1. `carPrice = Number(carPrice.replaceAll(",", ""));` on line 4 +// 2. `priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", ""));` on line 5 + +// d) The variable declarations are: +// 1. `let carPrice = "10,000";` on line 1 +// 2. `let priceAfterOneYear = "8,543";` on line 2 +// 3. `const priceDifference = carPrice - priceAfterOneYear;` on line 7 +// 4. `const percentageChange = (priceDifference / carPrice) * 100;` on line 8 + +// e) The expression `Number(carPrice.replaceAll(",", ""))` is converting the string representation of the car price (which includes commas) into a number. +// The `replaceAll(",", "")` part removes all commas from the string, and then the `Number()` function converts the resulting string into a numeric value. \ 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..20afb8e03 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 = 8314.5; // length of movie in seconds const remainingSeconds = movieLength % 60; const totalMinutes = (movieLength - remainingSeconds) / 60; @@ -23,3 +23,31 @@ console.log(result); // 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 + +// a) There are 6 variable declarations in this program: +// 1. `const movieLength = 8784;` +// 2. `const remainingSeconds = movieLength % 60;` +// 3. `const totalMinutes = (movieLength - remainingSeconds) / 60;` +// 4. `const remainingMinutes = totalMinutes % 60;` +// 5. `const totalHours = (totalMinutes - remainingMinutes) / 60;` +// 6. `const result = `${totalHours}:${remainingMinutes}:${remainingSeconds}`;` + +// b) There is 1 function calls in this program console.log(result);. + +// c) The expression `movieLength % 60` calculates the remainder when `movieLength` (the total length of the movie in seconds) is divided by 60. +// This gives the number of seconds that do not complete a full minute, effectively providing the remaining seconds after converting the total movie length into minutes. + +// d) The expression assigned to `totalMinutes` calculates the total number of minutes in the movie by subtracting the remaining seconds from the total movie length and then dividing by 60. +// It converts the total movie length from seconds to minutes, effectively giving the total number of complete minutes in the movie. + +// e) The variable `result` represents the total duration of the movie formatted as "hours:minutes:seconds". +// A better name for this variable could be `formattedMovieDuration` or `movieDurationFormatted` to make it clear that it contains the movie's duration in a specific format. + +// f) This code will work for all values of `movieLength` that are non-negative integers. +// However, if `movieLength` is negative, the calculations will still work but may not make sense in the context of a movie duration. +// If `movieLength` is a floating-point number, the output will still be formatted correctly, but the seconds and minutes may not be whole numbers. +// If `movieLength` is a very large number, the code will still function correctly, but the output may not be practical for real-world movie durations. +// The code assumes that `movieLength` is a valid non-negative number representing the length of a movie in seconds, and it will produce a formatted string representing that duration in hours, minutes, and seconds. +// The code does not handle cases where `movieLength` is not a number or is undefined, which could lead to unexpected results. +// The code is designed to handle typical movie lengths, but it may not be robust against all possible inputs. + diff --git a/Sprint-1/3-mandatory-interpret/3-to-pounds.js b/Sprint-1/3-mandatory-interpret/3-to-pounds.js index 60c9ace69..46820c132 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -25,3 +25,15 @@ 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): +// removes the trailing 'p' from the string, resulting in "399" +// 3. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"): +// pads the string with leading zeros to ensure it has at least 3 characters, resulting in "399" +// 4. const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2): +// extracts the pounds part of the string by taking all characters except the last two, resulting in "3" +// 5. const pence = paddedPenceNumberString +// .substring(paddedPenceNumberString.length - 2).padEnd(2, "0"): +// extracts the last two characters (the pence part) and pads it with trailing zeros to ensure it has 2 characters, resulting in "99" +// 6. console.log(`£${pounds}.${pence}`): +// prints the final formatted string representing the price in pounds, which is "£3.99" + diff --git a/Sprint-1/4-stretch-explore/chrome.md b/Sprint-1/4-stretch-explore/chrome.md index e7dd5feaf..17eab02a3 100644 --- a/Sprint-1/4-stretch-explore/chrome.md +++ b/Sprint-1/4-stretch-explore/chrome.md @@ -12,7 +12,28 @@ invoke the function `alert` with an input string of `"Hello world!"`; What effect does calling the `alert` function have? +A popup dialog appears in the browser window with the message "Hello world!" and an OK button. +It's a simple way to show a message to the user. + 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? +A popup appears that: + +Shows the message: "What is your name?" Includes a text input field + +Has OK and Cancel buttons + +The prompt blocks interaction with the page until it is dismissed. + +Most browsers style the prompt natively, so it cannot be customized with CSS or HTML. + +Overuse is discouraged in modern UI design in favor of custom modals or forms. + + What is the return value of `prompt`? +The prompt() function returns: + +The string the user types (e.g., "ٍSalah") + +null if the user clicks Cancel instead of OK \ No newline at end of file diff --git a/Sprint-1/4-stretch-explore/objects.md b/Sprint-1/4-stretch-explore/objects.md index 0216dee56..5b7981428 100644 --- a/Sprint-1/4-stretch-explore/objects.md +++ b/Sprint-1/4-stretch-explore/objects.md @@ -5,12 +5,44 @@ 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? +ƒ log() { [native code] } Now enter just `console` in the Console, what output do you get back? +console {debug: ƒ, error: ƒ, info: ƒ, log: ƒ, warn: ƒ, …} + Try also entering `typeof console` Answer the following questions: What does `console` store? +'object' + +The console object stores functions (methods) such as: + +console.log() – for general output + +console.error() – for error messages + +console.warn() – for warnings + +console.table() – for formatted table output + +console.time() and console.timeEnd() – for timing operations + +console.group() and console.groupEnd() – for grouping logs + +These methods don't store data themselves, but they give you tools to output and inspect data during runtime. + What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? +This syntax accesses a property or method on the console object. + +The dot (.) is called dot notation. + +console.log means: + +Look inside the console object + +Find the function named log + +So console.log("Hi") is calling the log method of the console 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..0d74db1b7 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -9,5 +9,13 @@ function capitalise(str) { return str; } -// =============> write your explanation here +// =============> write your explanation here +// The error occurs because the variable `str` is being redeclared inside the function, which is not allowed in JavaScript. +// The variable `str` is already defined as a parameter of the function, and attempting to declare it again with `let` causes a syntax error. +// + // =============> write your new code here +function capitalise(str) { + str = `${str[0].toUpperCase()}${str.slice(1)}`; + return str; +} diff --git a/Sprint-2/1-key-errors/1.js b/Sprint-2/1-key-errors/1.js index f2d56151f..da770a90b 100644 --- a/Sprint-2/1-key-errors/1.js +++ b/Sprint-2/1-key-errors/1.js @@ -2,19 +2,25 @@ // Why will an error occur when this program runs? // =============> write your prediction here - +// The error will occur because the variable `decimalNumber` is being redeclared with `const +// inside the function `convertToPercentage`, which is not allowed since `decimalNumber` is already defined as a parameter of the function. // 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); +//console.log(decimalNumber); // =============> write your explanation here +// The error occurs because the variable `decimalNumber` is being redeclared with `const` inside the function, +// which is not allowed since `decimalNumber` is already defined as a parameter of the function. // Finally, correct the code to fix the problem // =============> write your new code here +function convertToPercentage(decimalNumber) { + return `${decimalNumber * 100}%`; +} diff --git a/Sprint-2/1-key-errors/2.js b/Sprint-2/1-key-errors/2.js index aad57f7cf..a9b2a9f43 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -10,11 +10,20 @@ function square(3) { } // =============> write the error message here +// The error occurs because the function parameter is incorrectly defined as a number (3) instead of a variable name. + // =============> explain this error message here +// The error message indicates that the function parameter is not defined correctly. In JavaScript, function parameters should be variable names, not literal values. The number `3` is being used as a parameter name, which is invalid syntax. + // Finally, correct the code to fix the problem // =============> write your new code here +function square(num) { + return num * num; +} +// Now, you can call the function with a number to get the square +console.log(square(3)); // This will output 9, which is the square of 3. diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js index b27511b41..865f9700d 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -9,6 +9,11 @@ function multiply(a, b) { console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); // =============> write your explanation here +// The error occurs because the `multiply` function does not return a value; it only logs the result to the console. +// Therefore, when trying to use the result in the template literal, it results in `undefined` being printed. // Finally, correct the code to fix the problem // =============> write your new code here +function multiply(a, b) { + return a * b; // Return the result instead of logging it +} diff --git a/Sprint-2/2-mandatory-debug/1.js b/Sprint-2/2-mandatory-debug/1.js index 37cedfbcf..5308c0f07 100644 --- a/Sprint-2/2-mandatory-debug/1.js +++ b/Sprint-2/2-mandatory-debug/1.js @@ -9,5 +9,14 @@ function sum(a, b) { console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); // =============> write your explanation here +// The error occurs because the `return` statement is placed before the expression `a + b`, +// which means the function returns `undefined` instead of the sum of `a` and `b`. + // Finally, correct the code to fix the problem // =============> write your new code here +function sum(a, b) { + return a + b; // Return the sum of a and b +} +console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); // This will now correctly output the sum +// The output will be: The sum of 10 and 32 is 42 +// This indicates that the function now correctly computes and returns the sum of the two numbers. diff --git a/Sprint-2/2-mandatory-debug/2.js b/Sprint-2/2-mandatory-debug/2.js index 57d3f5dc3..67910c66f 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -15,10 +15,34 @@ 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 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 incorrect because the `getLastDigit` function is using a fixed variable `num` +// instead of taking the input number as an argument. Therefore, it always returns the last digit of `103`, +// which is `3`, regardless of the input provided in the console.log statements. + // Finally, correct the code to fix the problem // =============> write your new code here +function getLastDigit(num) { + return num.toString().slice(-1); +} +// Now the function takes a number as an argument and returns its last digit +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)}`); +// The last digit of 42 is 2 +// The last digit of 105 is 5 +// The last digit of 806 is 6 + // This program should tell the user the last digit of each number. // Explain why getLastDigit is not working properly - correct the problem +// The `getLastDigit` function was not working properly because it was using a fixed variable `num` +// instead of taking the input number as an argument. By modifying the function to accept a parameter, +// it now correctly returns the last digit of the provided number. The corrected function now works as intended, +// allowing it to return the last digit of any number passed to it as an argument. +// The final output now correctly displays the last digits of the numbers 42, 105, and 806 as 2, 5, and 6 respectively. diff --git a/Sprint-2/3-mandatory-implement/1-bmi.js b/Sprint-2/3-mandatory-implement/1-bmi.js index 17b1cbde1..6ef6c99ca 100644 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -16,4 +16,9 @@ function calculateBMI(weight, height) { // return the BMI of someone based off their weight and height -} \ No newline at end of file + const bmi = weight / (height * height); // Calculate BMI + return bmi.toFixed(1); // Return BMI rounded to 1 decimal place +} +// Example usage: +console.log(`The BMI for a person weighing 70kg and 1.73m tall is ${calculateBMI(104, 1.78)}`); +// Should output: The BMI for a person weighing 104kg and 1.78m tall is 32.8 \ 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 5b0ef77ad..33cf9abcc 100644 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -14,3 +14,12 @@ // You will need to come up with an appropriate name for the function // Use the MDN string documentation to help you find a solution // This might help https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase + +function toUpperSnakeCase(inputString) { + + // Convert the input string to uppercase and replace spaces with underscores + return inputString.toUpperCase().replace(/\s+/g, '_'); +} +// Example usage: +console.log(toUpperSnakeCase("hello there")); // Should output: "HELLO_THERE" +console.log(toUpperSnakeCase("lord of the rings")); // Should output: "LORD_OF_THE_RINGS" diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js index 6265a1a70..4b6b18272 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -4,3 +4,23 @@ // 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(amountInPence) { + // Remove the trailing 'p' from the string and convert to a number + const penceStringWithoutTrailingP=amountInPence.toString().replace('p', ''); + // Pad the string with leading zeros to ensure it has at least 3 characters + const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, '0'); + // Extract the pounds part of the string + const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2); + // Extract the pence part of the string and pad it with trailing zeros to ensure it has 2 characters + const pence = paddedPenceNumberString.substring(paddedPenceNumberString.length - 2).padEnd(2, '0'); + // Return the formatted string representing the price in pounds + return `£${pounds}.${pence}`; + } +// Example usage: +console.log(toPounds("399p")); // Should output: £3.99 +console.log(toPounds("100p")); // Should output: £1.00 +console.log(toPounds("50p")); // Should output: £0.50 +console.log(toPounds("999p")); // Should output: £9.99 +console.log(toPounds("1234p")); // Should output: £12.34 +console.log(toPounds("1p")); // Should output: £0.01 diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js index 7c98eb0e8..125bed7d1 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -11,6 +11,8 @@ 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 @@ -18,17 +20,17 @@ function formatTimeDisplay(seconds) { // a) When formatTimeDisplay is called how many times will pad be called? // =============> write your answer here +// When formatTimeDisplay is called, pad will be called 3 times: once for totalHours, +// once for remainingMinutes, and once for 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 +// When pad is called for the first time, the value assigned to num is 1. +// This is because totalHours is calculated as (61 - 1) / 60, which equals 1. +// The totalHours is 1, so pad is called with 1. -// c) What is the return value of pad is called for the first time? -// =============> 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 -// 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 +// c) What is the return value of pad is c \ 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..a31d2d153 100644 --- a/Sprint-2/5-stretch-extend/format-time.js +++ b/Sprint-2/5-stretch-extend/format-time.js @@ -3,23 +3,25 @@ // 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`; + let hours = Number(time.slice(0, 2)); + const minutes = time.slice(3, 5); + + let suffix = 'am'; + if (hours === 0) { + hours = 12; // midnight + } else if (hours === 12) { + suffix = 'pm'; // noon + } else if (hours > 12) { + hours -= 12; + suffix = 'pm'; } - return `${time} am`; + + const formattedHours = hours < 10 ? `0${hours}` : `${hours}`; + return `${formattedHours}:${minutes} ${suffix}`; } 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}` -); + `current output: ${cu \ No newline at end of file