diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 00000000..7f66bce6 Binary files /dev/null and b/.DS_Store differ diff --git a/week-1/.DS_Store b/week-1/.DS_Store new file mode 100644 index 00000000..fb6ad089 Binary files /dev/null and b/week-1/.DS_Store differ diff --git a/week-1/errors/0.js b/week-1/errors/0.js index cf6c5039..85e52911 100644 --- a/week-1/errors/0.js +++ b/week-1/errors/0.js @@ -1,2 +1,4 @@ -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? + +//answer. we comment the lines out like this \ No newline at end of file diff --git a/week-1/errors/1.js b/week-1/errors/1.js index 7a43cbea..997fc22e 100644 --- a/week-1/errors/1.js +++ b/week-1/errors/1.js @@ -2,3 +2,8 @@ const age = 33; age = age + 1; +// you cannot re-assign const instead we can use: let. + +//let age = 33; +//age = age + 1; + diff --git a/week-1/errors/2.js b/week-1/errors/2.js index e09b8983..31aa04f8 100644 --- a/week-1/errors/2.js +++ b/week-1/errors/2.js @@ -3,3 +3,8 @@ console.log(`I was born in ${cityOfBirth}`); const cityOfBirth = "Bolton"; + +// we should declare cityOfBirth before console.logging + +const cityOfBirth = "Bolton"; +console.log(`I was born in ${cityOfBirth}`); diff --git a/week-1/errors/3.js b/week-1/errors/3.js index ffa72ca4..1e300404 100644 --- a/week-1/errors/3.js +++ b/week-1/errors/3.js @@ -1,6 +1,11 @@ const cardNumber = 4533787178994213; const last4Digits = cardNumber.slice(-4); +//the card number must have a string format if we want to use the slice method + +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 // Make and explain a prediction about why the code won't work diff --git a/week-1/errors/4.js b/week-1/errors/4.js index 21dad8c5..66b2fbdb 100644 --- a/week-1/errors/4.js +++ b/week-1/errors/4.js @@ -1,2 +1,7 @@ const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; \ No newline at end of file +const 24hourClockTime = "08:53"; +// variables must start with letters + +const twelveHourClockTime = "20:53"; +const twentyFourhourClockTime = "08:53"; + diff --git a/week-1/exercises/count.js b/week-1/exercises/count.js index 117bcb2b..55fa0d71 100644 --- a/week-1/exercises/count.js +++ b/week-1/exercises/count.js @@ -1,6 +1,11 @@ let count = 0; -count = count + 1; +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 + +count = count + 1; //line three is increasing 0 by 1 and the = is the operator here.S + + + diff --git a/week-1/exercises/decimal.js b/week-1/exercises/decimal.js index bd4a4740..0e73d316 100644 --- a/week-1/exercises/decimal.js +++ b/week-1/exercises/decimal.js @@ -3,8 +3,16 @@ const num = 56.5467; // You should look up Math functions for this exercise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math -// Create a variable called wholeNumberPart and assign to it an expression that evaluates to 56 ( the whole number part of num ) -// Create a variable called decimalPart and assign to it an expression that evaluates to 0.5467 ( the decimal part of num ) -// Create a variable called roundedNum and assign to it an expression that evaluates to 57 ( num rounded to the nearest whole number ) +// Create a variable called wholeNumberPart and assign the whole number part of num to it +const wholeNumberPart = Math.floor(num); + +// Create a variable called decimalPart and assign the decimal part of num to it +const decimalPart = num - wholeNumberPart; + +// Create a variable called roundedNum and assign num rounded to the nearest whole number to it +const roundedNum = Math.round(num); + +console.log("Whole Number Part:", wholeNumberPart); +console.log("Decimal Part:", decimalPart); +console.log("Rounded Number:", roundedNum); -// Log your variables to the console to check your answers diff --git a/week-1/exercises/initials.js b/week-1/exercises/initials.js index 50b62103..dda054e1 100644 --- a/week-1/exercises/initials.js +++ b/week-1/exercises/initials.js @@ -4,3 +4,5 @@ let lastName = "Johnson"; // Declare a variable called initials that stores the first character of each string in upper case to form the user's initials // Log the variable in each case + +let initials = (firstName[0] + middleName[0] + lastName[0]).toUpperCase(); \ No newline at end of file diff --git a/week-1/exercises/paths.js b/week-1/exercises/paths.js index c91cd2ab..df9d0441 100644 --- a/week-1/exercises/paths.js +++ b/week-1/exercises/paths.js @@ -16,3 +16,34 @@ 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 filePath = "/Users/mitch/cyf/Module-JS1/week-1/interpret/file.txt"; + +// The index of the last slash +const lastSlashIndex = filePath.lastIndexOf("/"); + +// The "base" part from the filePath +const base = filePath.slice(lastSlashIndex + 1); + +// Logging the "base" part +console.log(`The base part of ${filePath} is ${base}`); + +//............................................................. + +// Extracting the "dir" part from the filePath +const dir = filePath.slice(0, lastSlashIndex); + +// The console-log +console.log(`The dir part of ${filePath} is ${dir}`); +//............................................................. + +// Extracting the "ext" part from the "base" part +const extIndex = base.lastIndexOf("."); +const ext = extIndex !== -1 ? base.slice(extIndex + 1) : "No extension"; + +// the console log +console.log(`The ext part of ${filePath} is ${ext}`); +//...................................................... + + diff --git a/week-1/exercises/random.js b/week-1/exercises/random.js index 79a4a4d5..189dcf5f 100644 --- a/week-1/exercises/random.js +++ b/week-1/exercises/random.js @@ -7,3 +7,8 @@ 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 several times to build an idea of what the program is doing + +//Answer + +// The variable -num- wil contain a random number between 1 and 100. + diff --git a/week-1/explore/chrome.md b/week-1/explore/chrome.md index e7dd5fea..d5450c6b 100644 --- a/week-1/explore/chrome.md +++ b/week-1/explore/chrome.md @@ -10,9 +10,15 @@ Let's try an example. In the Chrome console, invoke the function `alert` with an input string of `"Hello world!"`; + What effect does calling the `alert` function have? +// was unable to do this. it only worked when I used console.log. 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`? +.......................... + +// I was only able to use console.log \ No newline at end of file diff --git a/week-1/explore/objects.md b/week-1/explore/objects.md index 0216dee5..1d535000 100644 --- a/week-1/explore/objects.md +++ b/week-1/explore/objects.md @@ -5,8 +5,10 @@ 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? +`console.log` Now enter just `console` in the Console, what output do you get back? +`console` Try also entering `typeof console` @@ -14,3 +16,9 @@ Answer the following questions: What does `console` store? What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? + +The console.log() method prints a message to the web console.  + +The console.assert() method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. + +`.` means execute this”. \ No newline at end of file diff --git a/week-1/interpret/percentage-change.js b/week-1/interpret/percentage-change.js index 49b0ac15..03ef88e2 100644 --- a/week-1/interpret/percentage-change.js +++ b/week-1/interpret/percentage-change.js @@ -12,9 +12,13 @@ console.log(`The percentage change is ${percentageChange}`); // Read the code and then answer the questions below // a) How many function calls are there in this file? Write down all the lines where a function call is made +// ...........there are 2 function calls: 1) carPrice.replaceAll and 2) priceAfterOneYear.replaceAll // b) Identify all the lines that are variable reassignment statements +//.......1) carPrice = Number(carPrice.replaceAll(",", "")); and 2) priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); // c) Identify all the lines that are variable declarations +//.....1. `let carPrice = "10,000";` 2. `let priceAfterOneYear = "8,543";` 3. `const priceDifference = carPrice - priceAfterOneYear;` 4. `const percentageChange = (priceDifference / carPrice) * 100;` // d) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? +//..... it is replacing all the comas in the string so that we can have numbers that we can calculate. diff --git a/week-1/interpret/time-format.js b/week-1/interpret/time-format.js index 7961fe0d..83ebf4a5 100644 --- a/week-1/interpret/time-format.js +++ b/week-1/interpret/time-format.js @@ -13,17 +13,19 @@ 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? +// a) How many variable declarations are there in this program? There are five variable declarations in this program: -// b) How many function calls are there? +// b) How many function calls are there? There are zero function calls -// c) Using documentation on MDN, explain what the expression movieLength % 60 represents +// c) Using documentation on MDN, explain what the expression movieLength % 60 represents. it represents the reminder. +// (It calculates the remaining seconds after all the full minutes have been counted.) -// d) Interpret line 4, what does the expression assigned to totalMinutes mean? +// d) Interpret line 4, what does the expression assigned to totalMinutes mean? It extracts the seconds in the movie length. // e) What do you think the variable result represents? Can you think of a better name for this variable? +// the variable result represent (hours:minutes:seconds) time format, a better name would be (formattedTime) // f) Think about whether this program will work for all values of movieLength. // Think of what values may cause problems for the code. // Decide the result should be for those values, then test it out. -// Can you find any values of movieLength which don't give you what you'd expect? +// Can you find any values of movieLength which don't give you what you'd expect? yes, it is not considering (days) in the calculation. diff --git a/week-1/interpret/to-pounds.js b/week-1/interpret/to-pounds.js index 196be3b2..f3c37a85 100644 --- a/week-1/interpret/to-pounds.js +++ b/week-1/interpret/to-pounds.js @@ -27,3 +27,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); +// : This line creates a new string variable +// which represents the price in pence without the 'p' character. +// 3. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); +// : This line creates a new string variable with the value "399," +// 4. const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2); +// : This line takes the first character of the `paddedPenceNumberString`, +// which represents the pounds. +// 5. const pence = paddedPenceNumberString.substring(paddedPenceNumberString.length - 2).padEnd(2, "0"); +// : This line extracts the pence part of the `paddedPenceNumberString` +// 6. console.log(`£${pounds}.${pence}`); +// : This line combines the `pounds` and `pence` variables with the '£' symbol to to make it easy to read. + + + diff --git a/week-2/debug/0.js b/week-2/debug/0.js index b46d471a..c803e644 100644 --- a/week-2/debug/0.js +++ b/week-2/debug/0.js @@ -5,3 +5,14 @@ function multiply(a, b) { } console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); +localStorage + +// the result is showing 320, which is not fully correct due to the term LocalStorage. +// it should be written as below: + +function multiply(a, b) { + return a * b; +} + +console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); + diff --git a/week-2/debug/1.js b/week-2/debug/1.js index df4020ca..fe909206 100644 --- a/week-2/debug/1.js +++ b/week-2/debug/1.js @@ -1,8 +1,17 @@ // Predict and explain first... function sum(a, b) { - return; - a + b; + return; + a + b } + +//console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); + +// the semi colon in the return statement will stop the function execution. it should be as follows: + +function sum(a, b) { + return a + b; } console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); + + diff --git a/week-2/debug/2.js b/week-2/debug/2.js index bae9652a..10a86448 100644 --- a/week-2/debug/2.js +++ b/week-2/debug/2.js @@ -1,14 +1,25 @@ // Predict and explain first... -const num = 103; +// const num = 103; function getLastDigit() { - return num.toString().slice(-1); -} +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 +//........................................................................... +// first the (num) is not defined, second the (const num = 103;) is a fixed number and that is what it will +// calculate for all numbers, their last digit will remain 3, we can fix this by using +// the following code: + +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 diff --git a/week-2/errors/0.js b/week-2/errors/0.js index 58b1349d..d393a1c6 100644 --- a/week-2/errors/0.js +++ b/week-2/errors/0.js @@ -4,6 +4,24 @@ // interpret the error message and figure out why it's happening, if your prediction was wrong function capitalise(str) { - let str = `${str[0].toUpperCase()}${str.slice(1)}`; - return str; + let str = `${str[0].toUpperCase()}${str.slice(1)}`; + return str; } + +//.................................... +// the problem is that (str) is already the input to the function + +function capitalise(str) { + let capitalizedStr = `${str[0].toUpperCase()}${str.slice(1)}`; + return capitalizedStr; +} + +const originalString = "i love cyf"; +const capitalizedString = capitalise(originalString); + +console.log(`Original: ${originalString}`); +console.log(`Capitalized: ${capitalizedString}`); + + + + diff --git a/week-2/errors/1.js b/week-2/errors/1.js index 14b5b511..3d315a98 100644 --- a/week-2/errors/1.js +++ b/week-2/errors/1.js @@ -9,5 +9,36 @@ function convertToPercentage(decimalNumber) { return percentage; } +//................................. + +// ANSWER. +// We want the computer to perform a task: take the (decimalNumber ),, multiply it by 100, and add a '%' sign. +// However, we made a mistake by telling the computer "Hey computer, our special number is 'decimalNumber,' and by the way, it's 0.5!" +// This will confuse the computer and will result an error. To fix this, we need to correct our instructions, +// making sure that we only tell the computer about the (decimalNumber ) just once. If we solve this mistake, +// the computer will be able to carried out the task, (this is really a good example of how important is to give clear instructions, +// and how important is to avoid repetition in computer programming). + +//Playing computer results: + +// const decimalNumber is declared in the local scope +// const decimalNumber = 0.5; +// A syntax error occurs here because you're trying to redeclare 'decimalNumber' in the same scope. + +// const percentage = `${decimalNumber * 100}%`; +// This will not be reached due to the syntax error. + +// then we Called the function +// convertToPercentage(); +// This also results in a syntax error because we are trying to redeclare 'decimalNumber' in the same scope. + +function convertToPercentage() { + const decimalNumber = 0.5; + const percentage = `${decimalNumber * 100}%`; + + return percentage; +} + + +console.log(convertToPercentage()); -console.log(decimalNumber); diff --git a/week-2/errors/2.js b/week-2/errors/2.js index b0454133..0d720876 100644 --- a/week-2/errors/2.js +++ b/week-2/errors/2.js @@ -3,8 +3,19 @@ // this function should square any number but instead we're going to get an error // what is happening? How can we fix it? -function square(3) { - return num * num; -} +// function square(3) { +// return num * num; +// } + +//........................................... + +//ANSWER +function square(num) { + return num * num; + } + +console.log(square(4)); +console.log(square(7)); + diff --git a/week-2/implement/bmi.js b/week-2/implement/bmi.js index 172c7c9a..7edeb160 100644 --- a/week-2/implement/bmi.js +++ b/week-2/implement/bmi.js @@ -13,3 +13,27 @@ // Given someone's weight in kg and height in metres // When we call this function with the weight and height // Then it returns their Body Mass Index to 1 decimal place + +//.......................................... + +//ANSWERS + +function calculateBMI(weight, height) { + if (weight <= 0 || height <= 0) { + return "Invalid input. Please enter positive numbers for weight and height."; + } + + const heightSquared = height * height; + const bmi = weight / heightSquared; + + return Math.round(bmi * 10) / 10; + } + + const weight = 67; // in kg + const height = 1.73; // in meters + + const result = calculateBMI(weight, height); + console.log("BMI:", result); + + + diff --git a/week-2/implement/cases.js b/week-2/implement/cases.js index 56b0d8d0..7397d641 100644 --- a/week-2/implement/cases.js +++ b/week-2/implement/cases.js @@ -15,3 +15,22 @@ // Come up with a clear, simple name for the function // Use the string documentation to help you plan your solution + +//.......................................... + +// ANSWER + +function convertToUpperCaseWithUnderscores(inputString) { + + const words = inputString.split(" "); + + const upperCamelCaseString = words.map(word => word.toUpperCase()).join("_"); + + return upperCamelCaseString; + } + + // Test cases + console.log(convertToUpperCaseWithUnderscores("lord of the rings")); + console.log(convertToUpperCaseWithUnderscores("the great gatsby")); + console.log(convertToUpperCaseWithUnderscores("the da vinci code")); + diff --git a/week-2/implement/to-pounds.js b/week-2/implement/to-pounds.js index 7add3d05..17e744a3 100644 --- a/week-2/implement/to-pounds.js +++ b/week-2/implement/to-pounds.js @@ -3,3 +3,26 @@ // Take this code and turn it into a reusable block of code. // Declare a function called toPounds with an appropriately named parameter. // Call this function a number of times to check it works for different inputs +//..................................... + + +//ANSWER + +function toPounds(dollars) { + const exchangeRate = 0.73; + const pounds = dollars * exchangeRate; + return pounds; + } + + const amount1 = 50; + const amount2 = 100; + const amount3 = 50; + const amount4 = 100; + + console.log(`$${amount1} is £${toPounds(amount1).toFixed(2)}`); + console.log(`$${amount2} is £${toPounds(amount2).toFixed(2)}`); + console.log(`$${amount3} is £${toPounds(amount2).toFixed(2)}`); + console.log(`$${amount4} is £${toPounds(amount2).toFixed(2)}`); + + + \ No newline at end of file diff --git a/week-2/implement/vat.js b/week-2/implement/vat.js index 44c38d74..41977da9 100644 --- a/week-2/implement/vat.js +++ b/week-2/implement/vat.js @@ -8,3 +8,19 @@ // Given a number, // When I call this function with a number // Then it returns the new price with VAT added on +//......................................................... + +// ANSWER + +function calculatePriceWithVAT(originalPrice) { + const vatRate = 1.2; // 20% VAT rate + const priceWithVAT = originalPrice * vatRate; + return priceWithVAT; + } + + const originalPrice = 50; + const newPrice = calculatePriceWithVAT(originalPrice); + + console.log(`Original Price: £${originalPrice}`); + console.log(`New Price with VAT: £${newPrice.toFixed(2)}`); + \ No newline at end of file diff --git a/week-2/interpret/time-format.js b/week-2/interpret/time-format.js index 15793e20..49bba82c 100644 --- a/week-2/interpret/time-format.js +++ b/week-2/interpret/time-format.js @@ -41,3 +41,21 @@ console.log(formatTimeDisplay(143)); // f) Research an alternative way of padding the numbers in this code. // Look up the string functions on mdn +//.......................................................................... + +ANSWER + +// a) When we use `formatTimeDisplay`, we also use a helper called `pad` three times. We use it for hours, minutes, and seconds to make them look neat. + +// b) The first time we use `pad`, it helps us with the hours. It takes the total hours and divides them by 24 to get a special kind of hours. + +// c) The result we get from the first use of `pad` is a string that represents the hours, but it has zeros added in front to make it look good in our time display. + +// d) The last time we use `pad` in this program, it helps with the seconds. We give it the number of seconds, and it adds zeros in front to make it look nice. + +// e) The final result we get from the last use of `pad` is a string representing the seconds, but it's formatted with zeros in front to fit well in our time display. + +// f) There's another method called `String.prototype.padStart()`. It's like another tool we can use to make our numbers look neat. Here's an example: + + +// function pad(num) { return String(num).padStart(2, '0');}clear diff --git a/week-3/debug/format-as-12-hours.js b/week-3/debug/format-as-12-hours.js index 56b83a5b..56121060 100644 --- a/week-3/debug/format-as-12-hours.js +++ b/week-3/debug/format-as-12-hours.js @@ -28,3 +28,53 @@ console.assert( // a) Write an assertion to check the return value of formatAs12HourClock when it is called with an input "17:42" // b) Check the assertion output and explain what the bug is // c) Now fix the bug and re-run all your assertions + +//.......................................................... + +//ANSWER + +// a) Writing the assertion: +const currentOutput3 = formatAs12HourClock("17:42"); +const targetOutput3 = "5:42 pm"; +console.assert( + currentOutput3 === targetOutput3, + "current output: %s, target output: %s", + currentOutput3, + targetOutput3 +); + + +// b) The bug is: when the hour is greater than 12 it gives a wrong answer. +// for example When the input time is "17:42," it takes away 12 from the hour and returns "5:00 pm" +// instead of "5:42 pm." + +// c) fixing the bug + + +// First wee need to format time in 12-hour clock +function formatAs12HourClock(time) { + // second we need to Extract hour and minute from the time + const hour = Number(time.slice(0, 2)); + const minute = time.slice(3); + + // Then we need to check if the hour is greater than 12 + if (hour > 12) { + // in that case we will take away 12 from the hour and add "pm" + return `${hour - 12}:${minute} pm`; + } else { + // otherwise we will keep the hour as is and add "am" + return `${hour}:${minute} am`; + } +} + + + + + + + + + + + + diff --git a/week-3/implement/get-angle-type.js b/week-3/implement/get-angle-type.js index 9dd3a210..8b4d0dcd 100644 --- a/week-3/implement/get-angle-type.js +++ b/week-3/implement/get-angle-type.js @@ -21,3 +21,30 @@ // Identify Reflex Angles: // When the angle is greater than 180 degrees and less than 360 degrees, // Then the function should return "Reflex angle" + +// Function to identify the type of angle +//............................................... + +//Answer + + +function getAngleType(angle) { + if (angle === 90) { + return "Right angle"; + } + else if (angle < 90) { + return "Acute angle"; + } + else if (angle > 90 && angle < 180) { + return "Obtuse angle"; + } + else if (angle === 180) { + return "Straight angle"; + } + else if (angle > 180 && angle < 360) { + return "Reflex angle"; + } + else { + return "Unknown angle"; + } + } diff --git a/week-3/implement/get-card-value.js b/week-3/implement/get-card-value.js index 0dd74fbc..c34d13f4 100644 --- a/week-3/implement/get-card-value.js +++ b/week-3/implement/get-card-value.js @@ -29,3 +29,32 @@ // Given a card with an invalid rank (neither a number nor a recognized face card), // When the function is called with such a card, // Then it should throw an error indicating "Invalid card rank." +//........................................................... + +//ANSWER + + +function getCardValue(card) { + // first we need to extract the rank and leave the name + const rank = card.slice(0, -1); + // second we need to check if the card is a number card (2-10) + if (/^[2-9]|10$/.test(rank)) { + // Return the number value of the card + return parseInt(rank); + } + // next we need to check if the card is (J, Q, K) + else if (rank === "J" || rank === "Q" || rank === "K") { + // these cards are worth 10 points + return 10; + } + // then we check if the card is an Ace (A) + else if (rank === "A") { + // Aces are worth 11 points + return 11; + } + // after that If the card is not recognized, show an error + else { + // Show an error message for cards we don't understand + throw new Error("Invalid card."); + } + } diff --git a/week-3/implement/is-proper-fraction.js b/week-3/implement/is-proper-fraction.js index 31da32b5..5d05ca3a 100644 --- a/week-3/implement/is-proper-fraction.js +++ b/week-3/implement/is-proper-fraction.js @@ -33,3 +33,41 @@ // Explanation: The fraction 3/3 is not a proper fraction because the numerator is equal to the denominator. The function should return false. // These acceptance criteria cover a range of scenarios to ensure that the isProperFraction function handles both proper and improper fractions correctly and handles potential errors such as a zero denominator. + +///............................................... + + + +function isProperFraction(numerator, denominator) { + if (denominator === 0) { + return undefined; + } + if (numerator < denominator && numerator >= 0) { + return true; + } else { + return false; + } + } + + // Test cases for each acceptance criterion + +// // Proper Fraction check + const testProperFraction = isProperFraction(2, 3); + console.assert(testProperFraction === true); + +// // Improper Fraction check + const testImproperFraction = isProperFraction(5, 2); + console.assert(testImproperFraction === false); + + // Zero Denominator check + const testZeroDenominator = isProperFraction(3, 0); + console.assert(testZeroDenominator === undefined); + + // Negative Fraction check + const testNegativeFraction = isProperFraction(-4, 7); + console.assert(testNegativeFraction === true); + + // Equal Numerator and Denominator check + const testEqualNumeratorDenominator = isProperFraction(3, 3); + console.assert(testEqualNumeratorDenominator === false); + \ No newline at end of file diff --git a/week-3/implement/is-valid-triangle.js b/week-3/implement/is-valid-triangle.js index 7b22836b..b6408630 100644 --- a/week-3/implement/is-valid-triangle.js +++ b/week-3/implement/is-valid-triangle.js @@ -38,3 +38,35 @@ // Then it should return true because the input forms a valid triangle. // This specification outlines the behavior of the isValidTriangle function for different input scenarios, ensuring it properly checks for invalid side lengths and whether they form a valid triangle according to the Triangle Inequality Theorem. +//.................................................................... +//Answer + +// we start with a function to check if three numbers can form a triangle +function isValidTriangle(a, b, c) { + // here we are saying that sides should be greater than zero + if (a <= 0 || b <= 0 || c <= 0) { + return false; + } + + // then we need to check if the sum of any two sides is greater than the length of the third side for all possible combinations of sides + if (a + b > c && a + c > b && b + c > a) { + return true; // this means it is a valid triangle + } else { + return false; // It's not a valid triangle + } + } + + // Test examples + + // Test for (Invalid )Triangle + const testInvalidTriangle = isValidTriangle(2, 3, 6); + console.assert(testInvalidTriangle === false); + + // Test for Invalid Input: A side is less than or equal to zero + const testInvalidInput = isValidTriangle(0, 4, 5); + console.assert(testInvalidInput === false); + + // Test for a Valid Triangle + const testValidTriangle = isValidTriangle(3, 4, 5); + console.assert(testValidTriangle === true); + \ No newline at end of file diff --git a/week-3/refactor/format-as-12-hours.js b/week-3/refactor/format-as-12-hours.js index 41603122..0e63c9e1 100644 --- a/week-3/refactor/format-as-12-hours.js +++ b/week-3/refactor/format-as-12-hours.js @@ -4,3 +4,34 @@ // Store this expression in a variable and reference it twice in the function in the correct place // Explain why it makes more sense to store this expression in a variable +//........................................ + + +//Answer +function convertTo12HourFormat(time) { + // first we need to get the number of hours from the time + const hours = Number(time.slice(0, 2)); + + // If it's after noon (more than 12 o'clock), we will adjust the time format + if (hours > 12) { + return `${hours - 12}:00 PM`; + } + + // If it's before noon, we will keep the time format as it is + return `${time} AM`; + } + + //Examples: + +// // Example 1: Converting "08:00" to 12-hour format + const time1 = convertTo12HourFormat("08:00"); + const expectedTime1 = "08:00 AM"; + console.assert( + time1 === expectedTime1); + + // Example 2: Converting "23:00" to 12-hour format + const time2 = convertTo12HourFormat("23:00"); + const expectedTime2 = "11:00 PM"; + console.assert( + time2 === expectedTime2); + diff --git a/week-3/refactor/is-vowel.js b/week-3/refactor/is-vowel.js index db675d2b..5eff8d40 100644 --- a/week-3/refactor/is-vowel.js +++ b/week-3/refactor/is-vowel.js @@ -1,13 +1,29 @@ +// function isVowel(letter) { +// return ( +// letter === "a" || +// letter === "e" || +// letter === "i" || +// letter === "i" || +// letter === "o" || +// letter === "u" +// ); +// } +//............................................... + +//ANSWER +//The letter (i) is included two times, that is why i commented it out +// otherwise the code is fine when on (i) is removed. + function isVowel(letter) { return ( letter === "a" || letter === "e" || letter === "i" || - letter === "i" || letter === "o" || letter === "u" ); } +localStorage // here is an implementation of isVowel - this function checks if a letter is a vowel @@ -40,3 +56,4 @@ console.assert( currentOutput3, targetOutput3 ); + diff --git a/week-4/implement/card-validator.test.js b/week-4/implement/card-validator.test.js new file mode 100644 index 00000000..f056dec4 --- /dev/null +++ b/week-4/implement/card-validator.test.js @@ -0,0 +1,53 @@ + + +// This is a function that will validate the credit card number +function isCreditCardValid(cardNumber) { + // Here we are checking if the card number is a string; if not, we are converting it to a string + let cleanedCardNumber = (typeof cardNumber === 'string') ? cardNumber.replace(/[^0-9]/g, '') : ''; + + // Here we are checking if the cardNumber meets the specified criteria for validity + return ( + cleanedCardNumber.length === 16 && + hasAtLeastTwoDifferentDigits(cleanedCardNumber) && + isFinalDigitEven(cleanedCardNumber) && + isSumGreaterThan16(cleanedCardNumber) + ); +} + +// This is a helper function to check if there are at least two different digits in the number +function hasAtLeastTwoDifferentDigits(numbers) { + // then it converts the string into an array of unique numbers and check if the length is greater than or equal to 2 + return new Set(numbers.split('')).size >= 2; +} + +// The helper function then checks if the final digit is even +function isFinalDigitEven(numbers) { + // it then converts the last digit to a number and checks if it's even + return parseInt(numbers[numbers.length - 1], 10) % 2 === 0; +} + +// our helper function is here to check if the sum of all numbers is greater than 16 +function isSumGreaterThan16(numbers) { + // it Calculates the sum of all digits and checks if it's greater than 16 + return numbers.split('').reduce((sum, digit) => sum + parseInt(digit, 10), 0) > 16; +} + + + +//testing using npm test + + +test('Valid Credit Card Number', () => { + const validCardNumber = '9999777788880000'; + expect(isCreditCardValid(validCardNumber)).toBe(true); +}); + +test('Invalid Credit Card Number (Invalid Characters)', () => { + const invalidCardNumber = 'a92332119c011112'; + expect(isCreditCardValid(invalidCardNumber)).toBe(false); +}); + +test('Invalid Credit Card Number (One Type of Number)', () => { + const invalidCardNumber = '4444444444444444'; + expect(isCreditCardValid(invalidCardNumber)).toBe(false); +}); diff --git a/week-4/implement/count.test.js b/week-4/implement/count.test.js index 77a713a1..c590afe4 100644 --- a/week-4/implement/count.test.js +++ b/week-4/implement/count.test.js @@ -1,5 +1,7 @@ // implement a function countChar that counts the number of times a character occurs in a string +//const { default: test } = require("node:test"); + // Given a string str and a single character char to search for, // When the countChar function is called with these inputs, // Then it should: @@ -15,3 +17,34 @@ // And a character char that does not exist within the case-sensitive str, // When the function is called with these inputs, // Then it should return 0, indicating that no occurrences of the char were found in the case-sensitive str. + +/////.................................................................................................... +//ANSWER + +// count.js +function countChar(str, char) { + let count = 0; + for (let i = 0; i < str.length; i++) { + if (str[i] === char) { + count++; + while (str[i + 1] === char) { + i++; + count++; + } + } + } + + return count; +} + + +test('counts occurrences of a character in a string', () => { + const inputString = "aaaaaaa"; + const targetChar = "a"; + const currentOutput = countChar(inputString, targetChar); + const targetOutput = 7; + expect(currentOutput).toBe(targetOutput); +}); + + + diff --git a/week-4/implement/get-ordinal-number.test.js b/week-4/implement/get-ordinal-number.test.js index 4e735d0b..ab361f2f 100644 --- a/week-4/implement/get-ordinal-number.test.js +++ b/week-4/implement/get-ordinal-number.test.js @@ -2,3 +2,47 @@ // continue testing and implementing getOrdinalNumber for additional cases // Write your tests using Jest - remember to run your tests often for continual feedback +//............................................. +//ANSWER + + + +// getOrdinalNumber(1); // returns "1st"; +// getOrdinalNumber(2); // returns "2nd"; +// getOrdinalNumber(6); // returns "6th"; + +function getOrdinalNumber(number) { + const suffix = getSuffix(number); + return `${number}${suffix}`; + } + + function getSuffix(number) { + const lastDigit = number % 10; + const lastTwoDigits = number % 100; + + if (lastTwoDigits >= 11 && lastTwoDigits <= 13) { + return 'th'; + } + + if (lastDigit === 1) { + return 'st'; + } else if (lastDigit === 2) { + return 'nd'; + } else if (lastDigit === 3) { + return 'rd'; + } else { + return 'th'; + } + } + + +// new way of checking code using jest +test("converts 1 to an ordinal number", function () { + const input = 6; + const currentOutput = getOrdinalNumber(input); + const targetOutput = "6th"; + + expect(currentOutput).toBe(targetOutput); + }); + + diff --git a/week-4/implement/is-prime.test.js b/week-4/implement/is-prime.test.js index 90199887..209a64f4 100644 --- a/week-4/implement/is-prime.test.js +++ b/week-4/implement/is-prime.test.js @@ -1,3 +1,37 @@ // Given a positive integer num, // When the isPrime function is called with num as input, // Then it should return a boolean representing whether the num is prime + +//................................................................ + +// ANSWER + +function isPrime(num) { + if (num <= 1) { + return false; // 0 and 1 are not prime numbers + } + + for (let i = 2; i <= Math.sqrt(num); i++) { + if (num % i === 0) { + return false; + } + } + + return true; + } + + test('returns true for prime number 7', () => { + expect(isPrime(7)).toBe(true); + }); + + test('returns false for non-prime number 12', () => { + expect(isPrime(12)).toBe(false); + }); + + test('returns false for 1', () => { + expect(isPrime(1)).toBe(false); + }); + + test('returns false for 0', () => { + expect(isPrime(0)).toBe(false); + }); \ No newline at end of file diff --git a/week-4/implement/password-validator.test.js b/week-4/implement/password-validator.test.js index dfc7cedb..f400c3d3 100644 --- a/week-4/implement/password-validator.test.js +++ b/week-4/implement/password-validator.test.js @@ -14,3 +14,36 @@ To be valid, a password must: You must breakdown this problem in order to solve it. Find one test case first and get that working */ + + + +function isPasswordValid(password, previousPasswords = []) { + if (password.length < 5) { + return false; + } + if (!/[A-Z]/.test(password)) { + return false; + } + if (!/[a-z]/.test(password)) { + return false; + } + if (!/\d/.test(password)) { + return false; + } + if (!/[!#$%.&*]/.test(password)) { + return false; + } + if (previousPasswords.includes(password)) { + return false; + } + return true; + } + + + + test('returns true for a valid password meeting all criteria', () => { + const password = 'Secure123!'; + const previousPasswords = ['WeakPassword1!', 'InsecurePass2']; + expect(isPasswordValid(password, previousPasswords)).toBe(true); + }); + \ No newline at end of file diff --git a/week-4/implement/repeat.test.js b/week-4/implement/repeat.test.js index 0b2b0a3e..ab33501c 100644 --- a/week-4/implement/repeat.test.js +++ b/week-4/implement/repeat.test.js @@ -23,3 +23,39 @@ // Given a target string str and a negative integer count, // When the repeat function is called with these inputs, // Then it should throw an error or return an appropriate error message, as negative counts are not valid. +//............................................ +//Answer + +function repeat(str, count) { + if (count < 0) { + throw new Error('Negative count is not valid'); + } + + if (count === 0) { + return ''; + } + + return str.repeat(count); + } + + module.exports = repeat; + + + test('repeat String: repeats the string count times', () => { + const result = repeat('abc', 3); + expect(result).toBe('abcabcabc'); + }); + + test('handle Count of 1: returns the original string without repetition', () => { + const result = repeat('xyz', 1); + expect(result).toBe('xyz'); + }); + + test('Handle Count of 0: returns an empty string', () => { + const result = repeat('123', 0); + expect(result).toBe(''); + }); + + test('Negative Count: throws an error for negative count', () => { + expect(() => repeat('hello', -2)).toThrow('Negative count is not valid'); + }); \ No newline at end of file diff --git a/week-4/investigate/find.js b/week-4/investigate/find.js index c7e79a2f..76e3c0f5 100644 --- a/week-4/investigate/find.js +++ b/week-4/investigate/find.js @@ -23,3 +23,26 @@ console.log(find("code your future", "z")); // b) What is the if statement used to check // c) Why is index++ being used? // d) What is the condition index < str.length used for? + +//................................................................................................................ + +//ANSWER + +// We have line of letters "code your future." and we want to find a specific letter in this line, letter "u." + +// This function called "find" is like a little helper that looks at each letter in the line, one by one. It starts at the beginning and keeps going until it either finds the letter "u" or looks at every letter in the line. + +// Here's what the function called “find” which is our helper does step by step: + +// a) The helper uses a special counter, which we called "index". It starts at the beginning (the first letter), and each time it checks a letter, it moves to the next one. So, it goes from the first letter, then the second, then the third, and so on. + +// b) When the helper looks at a letter, it asks a question: "Is this letter the one we're looking for?" It uses a special rule (===) to check if the letter it's looking at is the same as the one we want to find. + +// c) The helper uses a trick called “Incrementing." to look at each letter one after the other. It does this by adding 1 to its counter, which we call “index”. + +// d) The condition “index < str.length" is used : because we don’t want our helper to go too far and look at letters that aren't there. So, it has a rule: something like: I’ll keep looking as long as I haven't looked at all the letters in the line. It checks this rule before looking at each letter. It is only after it has looked at all the letters, then it stops. + +// So, when we ask the helper to find the letter "u" in our line, it looks through each letter until it finds the first "u." If it finds it, it tells us where it found it (which position), and if it doesn't find it, it says, "I didn't find it," and tells us -1. + +// In our example, it found the first "u" at position 2 (because we start counting from 0), and it didn't find "z," so it says -1. +