diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js index 117bcb2b6..b4dfaf57d 100644 --- a/Sprint-1/1-key-exercises/1-count.js +++ b/Sprint-1/1-key-exercises/1-count.js @@ -4,3 +4,6 @@ count = count + 1; // Line 1 is a variable declaration, creating the count variable with an initial value of 0 // Describe what line 3 is doing, in particular focus on what = is doing +//Answer: +// Line 3 takes the current value of `count`, adds 1, and assigns the result back to `count`. +// The = operator is the assignment operator. diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js index 47561f617..0625c84e2 100644 --- a/Sprint-1/1-key-exercises/2-initials.js +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -5,7 +5,9 @@ let lastName = "Johnson"; // Declare a variable called initials that stores the first character of each string. // This should produce the string "CKJ", but you must not write the characters C, K, or J in the code of your solution. -let initials = ``; - +let initials = firstName[0] + middleName[0] + lastName[0]; +console.log(initials) // https://www.google.com/search?q=get+first+character+of+string+mdn +// The variable 'initials' takes the first character of firstName, middleName, and lastName, +// and combines them to form a new string. diff --git a/Sprint-1/1-key-exercises/3-paths.js b/Sprint-1/1-key-exercises/3-paths.js index ab90ebb28..24125e26c 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -17,7 +17,8 @@ console.log(`The base part of ${filePath} is ${base}`); // Create a variable to store the dir part of the filePath variable // Create a variable to store the ext part of the variable -const dir = ; -const ext = ; +const dir = filePath.slice(0, lastSlashIndex); +const lastDotIndex = base.lastIndexOf("."); +const ext = base.slice(lastDotIndex); // 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..dd4efae08 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -7,3 +7,9 @@ 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 +//Answer: +// The variable 'num' stores a random integer between 'minimum' (1) and 'maximum' (100), inclusive. +// Math.random() generates a random number from 0 up to (but not including) 1. +// Multiplying by (maximum - minimum + 1) scales it to the desired range. +// Math.floor() rounds down to the nearest whole number. +// Adding 'minimum' shifts the range so it starts at 1 instead of 0. diff --git a/Sprint-1/2-mandatory-errors/0.js b/Sprint-1/2-mandatory-errors/0.js index cf6c5039f..65ad3030d 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? \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/1.js b/Sprint-1/2-mandatory-errors/1.js index 7a43cbea7..a43815fa9 100644 --- a/Sprint-1/2-mandatory-errors/1.js +++ b/Sprint-1/2-mandatory-errors/1.js @@ -1,4 +1,9 @@ // 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); + +// We use 'let' to create a variable that can be reassigned. +// 'age' starts at 33, then we add 1 to it and store the result back in 'age'. +// console.log(age) outputs 34. diff --git a/Sprint-1/2-mandatory-errors/2.js b/Sprint-1/2-mandatory-errors/2.js index e09b89831..32f1e1757 100644 --- a/Sprint-1/2-mandatory-errors/2.js +++ b/Sprint-1/2-mandatory-errors/2.js @@ -1,5 +1,9 @@ // Currently trying to print the string "I was born in Bolton" but it isn't working... // what's the error ? -console.log(`I was born in ${cityOfBirth}`); const cityOfBirth = "Bolton"; +console.log(`I was born in ${cityOfBirth}`); + +// The error was that the variable 'cityOfBirth' was used before it was declared. +// Using 'const', a variable must be declared before it can be accessed. +// Correct order: first declare the variable, then use it in console.log. \ 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..b14101a00 100644 --- a/Sprint-1/2-mandatory-errors/3.js +++ b/Sprint-1/2-mandatory-errors/3.js @@ -1,5 +1,6 @@ const cardNumber = 4533787178994213; -const last4Digits = cardNumber.slice(-4); +const last4Digits = cardNumber.toString().slice(-4); +console.log(last4Digits); // The last4Digits variable should store the last 4 digits of cardNumber // However, the code isn't working diff --git a/Sprint-1/2-mandatory-errors/4.js b/Sprint-1/2-mandatory-errors/4.js index 21dad8c5d..e95cc0fe0 100644 --- a/Sprint-1/2-mandatory-errors/4.js +++ b/Sprint-1/2-mandatory-errors/4.js @@ -1,2 +1,8 @@ -const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; \ No newline at end of file +const hour12ClockTime = "20:53"; +const hour24ClockTime = "08:53"; + +console.log(hour12ClockTime); +console.log(hour24ClockTime); + +// Variable names cannot start with a number, so I use hour12ClockTime and hour24ClockTime. +// This way the code works and prints the correct times. diff --git a/Sprint-1/3-mandatory-interpret/1-percentage-change.js b/Sprint-1/3-mandatory-interpret/1-percentage-change.js index e24ecb8e1..1256e050f 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,26 @@ 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? + + +//Answer: +// a) Function calls are on these lines: +// carPrice = Number(carPrice.replaceAll(",", "")); +// priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); +// console.log(`The percentage change is ${percentageChange}`); + +// b) Error occurs on the line: +// priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); +// Reason: missing comma between arguments of replaceAll. Fix: replaceAll(",", "") + +// c) Variable reassignment lines: +// carPrice = Number(carPrice.replaceAll(",", "")); +// priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); + +// d) Variable declaration lines: +// let carPrice = "10,000"; +// let priceAfterOneYear = "8,543"; +// const priceDifference = carPrice - priceAfterOneYear; +// const percentageChange = (priceDifference / carPrice) * 100; + +// e) Number(carPrice.replaceAll(",", "")) removes all commas from the string and converts it to a number so calculations can be done. diff --git a/Sprint-1/3-mandatory-interpret/2-time-format.js b/Sprint-1/3-mandatory-interpret/2-time-format.js index 47d239558..57613ce0a 100644 --- a/Sprint-1/3-mandatory-interpret/2-time-format.js +++ b/Sprint-1/3-mandatory-interpret/2-time-format.js @@ -23,3 +23,18 @@ 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 + +//Answer: +// a) Variable declarations: +// movieLength, remainingSeconds, totalMinutes, remainingMinutes, totalHours, result (6 in total) + +// b) Function calls: +// console.log(result) (1 function call) + +// c) movieLength % 60 gives the remainder when movieLength is divided by 60, representing the remaining seconds after full minutes are counted + +// d) totalMinutes = (movieLength - remainingSeconds) / 60 calculates the total number of full minutes by removing leftover seconds and dividing by 60 + +// e) result represents the movie duration in hours:minutes:seconds format. A better name could be formattedMovieLength or movieTimeString + +// f) The code works for any positive number of seconds, but single-digit minutes or seconds will not have leading zeros. To fix this, use padStart to format as hh:mm:ss diff --git a/Sprint-1/3-mandatory-interpret/3-to-pounds.js b/Sprint-1/3-mandatory-interpret/3-to-pounds.js index 60c9ace69..822fc041f 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -1,21 +1,27 @@ const penceString = "399p"; +// Initialize a string variable with the value "399p" const penceStringWithoutTrailingP = penceString.substring( 0, penceString.length - 1 ); - +//Remove the trailing "p" from the string to get just the number part, e.g. "399" const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); +// Ensure the string has at least 3 characters by adding leading zeros if needed, e.g. "399" stays "399", "5" becomes "005" + const pounds = paddedPenceNumberString.substring( 0, paddedPenceNumberString.length - 2 ); +// Take all but the last two characters to get the pounds part, e.g. "3" from "399" const pence = paddedPenceNumberString .substring(paddedPenceNumberString.length - 2) .padEnd(2, "0"); +// Take the last two characters for the pence part. If less than 2 characters, add a zero at the end, e.g. "99" from "399" console.log(`£${pounds}.${pence}`); +// Combine pounds and pence into a formatted string and print, e.g. "£3.99" // This program takes a string representing a price in pence // The program then builds up a string representing the price in pounds diff --git a/Sprint-1/4-stretch-explore/chrome.md b/Sprint-1/4-stretch-explore/chrome.md index e7dd5feaf..4f36a97ef 100644 --- a/Sprint-1/4-stretch-explore/chrome.md +++ b/Sprint-1/4-stretch-explore/chrome.md @@ -16,3 +16,12 @@ Now try invoking the function `prompt` with a string input of `"What is your nam What effect does calling the `prompt` function have? What is the return value of `prompt`? + +Answer: +Calling alert("Hello world!") shows a popup with the message "Hello world!" to the user. +The alert function does not return any value (returns undefined). +Calling prompt("What is your name?") shows a popup with a text input field asking the user for their name. +The return value of prompt is the text entered by the user, or null if the user presses Cancel. +Example: +const myName = prompt("What is your name?"); +console.log(myName); // will display the name entered or null diff --git a/Sprint-1/4-stretch-explore/objects.md b/Sprint-1/4-stretch-explore/objects.md index 0216dee56..0ca2303b5 100644 --- a/Sprint-1/4-stretch-explore/objects.md +++ b/Sprint-1/4-stretch-explore/objects.md @@ -14,3 +14,13 @@ Answer the following questions: What does `console` store? What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? + + +Answer: +1. console stores an object that contains methods for logging and debugging, such as log, warn, error, assert, etc. +2. typeof console returns "object", confirming that console is an object. +3. console.log or console.assert uses the dot (.) syntax to access a method (function) of the console object. +The dot means "this method belongs to this object". +4. Example: +console.log("Hello"); // calls the log method of the console object +console.assert(1 === 2, "Not equal!"); // calls the assert method of the console object \ No newline at end of file diff --git a/Sprint-3/1-key-implement/1-get-angle-type.js b/Sprint-3/1-key-implement/1-get-angle-type.js index 08d1f0cba..68a219f4d 100644 --- a/Sprint-3/1-key-implement/1-get-angle-type.js +++ b/Sprint-3/1-key-implement/1-get-angle-type.js @@ -8,8 +8,11 @@ // Then, write the next test! :) Go through this process until all the cases are implemented function getAngleType(angle) { - if (angle === 90) return "Right angle"; - // read to the end, complete line 36, then pass your test here + if (angle === 90) return "Right angle"; // Case 1 + if (angle < 90) return "Acute angle"; // Case 2 + if (angle > 90 && angle < 180) return "Obtuse angle"; // Case 3 + if (angle === 180) return "Straight angle"; // Case 4 + if (angle > 180 && angle < 360) return "Reflex angle"; // Case 5 } // we're going to use this helper function to make our assertions easier to read @@ -43,14 +46,16 @@ assertEquals(acute, "Acute angle"); // When the angle is greater than 90 degrees and less than 180 degrees, // Then the function should return "Obtuse angle" const obtuse = getAngleType(120); -// ====> write your test here, and then add a line to pass the test in the function above +assertEquals(obtuse, "Obtuse angle"); // Case 4: Identify Straight Angles: // When the angle is exactly 180 degrees, // Then the function should return "Straight angle" -// ====> write your test here, and then add a line to pass the test in the function above +const straight = getAngleType(180); +assertEquals(straight, "Straight angle"); // Case 5: Identify Reflex Angles: // When the angle is greater than 180 degrees and less than 360 degrees, // Then the function should return "Reflex angle" -// ====> write your test here, and then add a line to pass the test in the function above \ No newline at end of file +const reflex = getAngleType(270); +assertEquals(reflex, "Reflex angle"); diff --git a/Sprint-3/1-key-implement/2-is-proper-fraction.js b/Sprint-3/1-key-implement/2-is-proper-fraction.js index 91583e941..20e18f6c5 100644 --- a/Sprint-3/1-key-implement/2-is-proper-fraction.js +++ b/Sprint-3/1-key-implement/2-is-proper-fraction.js @@ -8,7 +8,8 @@ // write one test at a time, and make it pass, build your solution up methodically function isProperFraction(numerator, denominator) { - if (numerator < denominator) return true; + // A proper fraction is when absolute value of numerator < denominator + return Math.abs(numerator) < denominator; } // here's our helper again @@ -40,14 +41,24 @@ assertEquals(improperFraction, false); // target output: true // Explanation: The fraction -4/7 is a proper fraction because the absolute value of the numerator (4) is less than the denominator (7). The function should return true. const negativeFraction = isProperFraction(-4, 7); -// ====> complete with your assertion +assertEquals(negativeFraction, true); // Equal Numerator and Denominator check: // Input: numerator = 3, denominator = 3 // target output: false // Explanation: The fraction 3/3 is not a proper fraction because the numerator is equal to the denominator. The function should return false. const equalFraction = isProperFraction(3, 3); -// ====> complete with your assertion +assertEquals(equalFraction, false); // Stretch: -// What other scenarios could you test for? +// Test zero numerator +const zeroNumerator = isProperFraction(0, 5); // 0/5 is proper +assertEquals(zeroNumerator, true); + +// Test negative denominator +const negativeDenominator = isProperFraction(2, -5); // numerator 2, denominator -5 => proper +assertEquals(negativeDenominator, true); + +// Test numerator larger negative than denominator +const largeNegativeNumerator = isProperFraction(-6, 5); // -6/5 is improper +assertEquals(largeNegativeNumerator, false); diff --git a/Sprint-3/1-key-implement/3-get-card-value.js b/Sprint-3/1-key-implement/3-get-card-value.js index aa1cc9f90..77760cbf0 100644 --- a/Sprint-3/1-key-implement/3-get-card-value.js +++ b/Sprint-3/1-key-implement/3-get-card-value.js @@ -7,45 +7,73 @@ // complete the rest of the tests and cases // write one test at a time, and make it pass, build your solution up methodically // just make one change at a time -- don't rush -- programmers are deep and careful thinkers + function getCardValue(card) { - if (rank === "A") return 11; + // Extract rank by removing the last character (suit) + const rank = card.slice(0, -1); + + // Ace + if (rank === "A") return 11; + + // Face cards + if (rank === "J" || rank === "Q" || rank === "K" || rank === "10") return 10; + + // Number cards + const numericRank = Number(rank); + if (numericRank >= 2 && numericRank <= 9) return numericRank; + + // Invalid card + throw new Error("Invalid card rank."); } -// You need to write assertions for your function to check it works in different cases -// we're going to use this helper function to make our assertions easier to read -// if the actual output matches the target output, the test will pass +// Helper function for assertions function assertEquals(actualOutput, targetOutput) { console.assert( actualOutput === targetOutput, `Expected ${actualOutput} to equal ${targetOutput}` ); } + // Acceptance criteria: -// Given a card string in the format "A♠" (representing a card in blackjack - the last character will always be an emoji for a suit, and all characters before will be a number 2-10, or one letter of J, Q, K, A), -// When the function getCardValue is called with this card string as input, -// Then it should return the numerical card value +// Ace of Spades const aceofSpades = getCardValue("A♠"); assertEquals(aceofSpades, 11); -// Handle Number Cards (2-10): -// Given a card with a rank between "2" and "9", -// When the function is called with such a card, -// Then it should return the numeric value corresponding to the rank (e.g., "5" should return 5). +// Number Card: 5 of Hearts const fiveofHearts = getCardValue("5♥"); -// ====> write your test here, and then add a line to pass the test in the function above - -// Handle Face Cards (J, Q, K): -// Given a card with a rank of "10," "J," "Q," or "K", -// When the function is called with such a card, -// Then it should return the value 10, as these cards are worth 10 points each in blackjack. - -// Handle Ace (A): -// Given a card with a rank of "A", -// When the function is called with an Ace, -// Then it should, by default, assume the Ace is worth 11 points, which is a common rule in blackjack. - -// Handle Invalid Cards: -// 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." +assertEquals(fiveofHearts, 5); + +// Face Card: King of Diamonds +const kingOfDiamonds = getCardValue("K♦"); +assertEquals(kingOfDiamonds, 10); + +// Face Card: Queen of Clubs +const queenOfClubs = getCardValue("Q♣"); +assertEquals(queenOfClubs, 10); + +// Number Card: 10 of Hearts +const tenOfHearts = getCardValue("10♥"); +assertEquals(tenOfHearts, 10); + +// Invalid Card: "1♠" +try { + getCardValue("1♠"); + console.assert(false, "Expected an error for invalid card"); +} catch (e) { + console.assert( + e.message === "Invalid card rank.", + `Unexpected error: ${e.message}` + ); +} + +// Invalid Card: "Z♣" +try { + getCardValue("Z♣"); + console.assert(false, "Expected an error for invalid card"); +} catch (e) { + console.assert( + e.message === "Invalid card rank.", + `Unexpected error: ${e.message}` + ); +} diff --git a/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js b/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js index d61254bd7..3dbb2540a 100644 --- a/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js +++ b/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js @@ -1,18 +1,12 @@ -function getAngleType(angle) { - if (angle === 90) return "Right angle"; - // replace with your completed function from key-implement +// Implement a function getAngleType +// Build up your function case by case, writing tests as you go +function getAngleType(angle) { + if (angle === 90) return "Right angle"; // Case 1 + if (angle < 90) return "Acute angle"; // Case 2 + if (angle > 90 && angle < 180) return "Obtuse angle"; // Case 3 + if (angle === 180) return "Straight angle"; // Case 4 + if (angle > 180 && angle < 360) return "Reflex angle"; // Case 5 } - - - - - - - -// Don't get bogged down in this detail -// Jest uses CommonJS module syntax by default as it's quite old -// We will upgrade our approach to ES6 modules in the next course module, so for now -// we have just written the CommonJS module.exports syntax for you -module.exports = getAngleType; \ No newline at end of file +module.exports = getAngleType; diff --git a/Sprint-3/2-mandatory-rewrite/1-get-angle-type.test.js b/Sprint-3/2-mandatory-rewrite/1-get-angle-type.test.js index b62827b7c..decaf3b80 100644 --- a/Sprint-3/2-mandatory-rewrite/1-get-angle-type.test.js +++ b/Sprint-3/2-mandatory-rewrite/1-get-angle-type.test.js @@ -4,21 +4,30 @@ test("should identify right angle (90°)", () => { expect(getAngleType(90)).toEqual("Right angle"); }); -// REPLACE the comments with the tests -// make your test descriptions as clear and readable as possible - -// Case 2: Identify Acute Angles: -// When the angle is less than 90 degrees, +// Case 2: Identify Acute Angles +// When the angle is less than 90 degrees // Then the function should return "Acute angle" +test("should identify acute angle (less than 90°)", () => { + expect(getAngleType(45)).toEqual("Acute angle"); +}); -// Case 3: Identify Obtuse Angles: -// When the angle is greater than 90 degrees and less than 180 degrees, +// Case 3: Identify Obtuse Angles +// When the angle is greater than 90 degrees and less than 180 degrees // Then the function should return "Obtuse angle" +test("should identify obtuse angle (between 90° and 180°)", () => { + expect(getAngleType(120)).toEqual("Obtuse angle"); +}); -// Case 4: Identify Straight Angles: -// When the angle is exactly 180 degrees, +// Case 4: Identify Straight Angles +// When the angle is exactly 180 degrees // Then the function should return "Straight angle" +test("should identify straight angle (180°)", () => { + expect(getAngleType(180)).toEqual("Straight angle"); +}); -// Case 5: Identify Reflex Angles: -// When the angle is greater than 180 degrees and less than 360 degrees, +// Case 5: Identify Reflex Angles +// When the angle is greater than 180 degrees and less than 360 degrees // Then the function should return "Reflex angle" +test("should identify reflex angle (between 180° and 360°)", () => { + expect(getAngleType(270)).toEqual("Reflex angle"); +}); diff --git a/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.js b/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.js index 9836fe398..51f90d425 100644 --- a/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.js +++ b/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.js @@ -1,6 +1,7 @@ function isProperFraction(numerator, denominator) { - if (numerator < denominator) return true; - // add your completed function from key-implement here + return Math.abs(numerator) < Math.abs(denominator); } -module.exports = isProperFraction; \ No newline at end of file +module.exports = isProperFraction; + +// add your completed function from key-implement here diff --git a/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.test.js b/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.test.js index ff1cc8173..7032715dc 100644 --- a/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.test.js +++ b/Sprint-3/2-mandatory-rewrite/2-is-proper-fraction.test.js @@ -5,7 +5,16 @@ test("should return true for a proper fraction", () => { }); // Case 2: Identify Improper Fractions: +test("should return false for an improper fraction", () => { + expect(isProperFraction(5, 2)).toEqual(false); +}); // Case 3: Identify Negative Fractions: +test("should return true for a negative proper fraction", () => { + expect(isProperFraction(-4, 7)).toEqual(true); +}); // Case 4: Identify Equal Numerator and Denominator: +test("should return false when numerator equals denominator", () => { + expect(isProperFraction(3, 3)).toEqual(false); +}); diff --git a/Sprint-3/2-mandatory-rewrite/3-get-card-value.js b/Sprint-3/2-mandatory-rewrite/3-get-card-value.js index 0d95d3736..574a4ca27 100644 --- a/Sprint-3/2-mandatory-rewrite/3-get-card-value.js +++ b/Sprint-3/2-mandatory-rewrite/3-get-card-value.js @@ -1,5 +1,10 @@ function getCardValue(card) { - // replace with your code from key-implement - return 11; + // replace with your code from key-implement + const rank = card.slice(0, -1); + if (rank === "A") return 11; + if (rank === "J" || rank === "Q" || rank === "K" || rank === "10") return 10; + const numericRank = Number(rank); + if (numericRank >= 2 && numericRank <= 9) return numericRank; + throw new Error("Invalid card rank."); } -module.exports = getCardValue; \ No newline at end of file +module.exports = getCardValue; diff --git a/Sprint-3/2-mandatory-rewrite/3-get-card-value.test.js b/Sprint-3/2-mandatory-rewrite/3-get-card-value.test.js index 03a8e2f34..7fde8d5ed 100644 --- a/Sprint-3/2-mandatory-rewrite/3-get-card-value.test.js +++ b/Sprint-3/2-mandatory-rewrite/3-get-card-value.test.js @@ -1,11 +1,29 @@ const getCardValue = require("./3-get-card-value"); test("should return 11 for Ace of Spades", () => { - const aceofSpades = getCardValue("A♠"); - expect(aceofSpades).toEqual(11); - }); + const aceofSpades = getCardValue("A♠"); + expect(aceofSpades).toEqual(11); +}); // Case 2: Handle Number Cards (2-10): +test("should return correct value for number cards", () => { + expect(getCardValue("2♦")).toEqual(2); + expect(getCardValue("5♥")).toEqual(5); + expect(getCardValue("9♣")).toEqual(9); +}); // Case 3: Handle Face Cards (J, Q, K): +test("should return 10 for face cards", () => { + expect(getCardValue("J♠")).toEqual(10); + expect(getCardValue("Q♥")).toEqual(10); + expect(getCardValue("K♦")).toEqual(10); +}); // Case 4: Handle Ace (A): +test("should return 11 for any Ace", () => { + expect(getCardValue("A♥")).toEqual(11); + expect(getCardValue("A♦")).toEqual(11); +}); // Case 5: Handle Invalid Cards: +test("should throw an error for invalid card rank", () => { + expect(() => getCardValue("1♠")).toThrow("Invalid card rank"); + expect(() => getCardValue("X♣")).toThrow("Invalid card rank"); +}); diff --git a/Sprint-3/3-mandatory-practice/implement/count.js b/Sprint-3/3-mandatory-practice/implement/count.js index fce249650..98516edd3 100644 --- a/Sprint-3/3-mandatory-practice/implement/count.js +++ b/Sprint-3/3-mandatory-practice/implement/count.js @@ -1,5 +1,10 @@ -function countChar(stringOfCharacters, findCharacter) { - return 5 +// implement a function countChar that counts the number of times a character occurs in a string +function countChar(str, char) { + let count = 0; + for (let i = 0; i < str.length; i++) { + if (str[i] === char) count++; + } + return count; } -module.exports = countChar; \ No newline at end of file +module.exports = countChar; diff --git a/Sprint-3/3-mandatory-practice/implement/count.test.js b/Sprint-3/3-mandatory-practice/implement/count.test.js index 42baf4b4b..cba6da4e8 100644 --- a/Sprint-3/3-mandatory-practice/implement/count.test.js +++ b/Sprint-3/3-mandatory-practice/implement/count.test.js @@ -1,15 +1,6 @@ -// implement a function countChar that counts the number of times a character occurs in a string const countChar = require("./count"); -// Given a string str and a single character char to search for, -// When the countChar function is called with these inputs, -// Then it should: // Scenario: Multiple Occurrences -// Given the input string str, -// And a character char that may occur multiple times with overlaps within str (e.g., 'a' in 'aaaaa'), -// When the function is called with these inputs, -// Then it should correctly count overlapping occurrences of char (e.g., 'a' appears five times in 'aaaaa'). - test("should count multiple occurrences of a character", () => { const str = "aaaaa"; const char = "a"; @@ -18,7 +9,25 @@ test("should count multiple occurrences of a character", () => { }); // Scenario: No Occurrences -// Given the input string str, -// 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. +test("should return 0 if character does not exist in string", () => { + const str = "hello"; + const char = "z"; + const count = countChar(str, char); + expect(count).toEqual(0); +}); + +// Scenario: Single Occurrence +test("should count a single occurrence of a character", () => { + const str = "hello"; + const char = "e"; + const count = countChar(str, char); + expect(count).toEqual(1); +}); + +// Scenario: Case-sensitive check +test("should be case-sensitive", () => { + const str = "aAaA"; + const char = "a"; + const count = countChar(str, char); + expect(count).toEqual(2); +}); diff --git a/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.js b/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.js index 24f528b0d..209bc591a 100644 --- a/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.js +++ b/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.js @@ -1,5 +1,13 @@ function getOrdinalNumber(num) { - return "1st"; + const j = num % 10, + k = num % 100; + if (k >= 11 && k <= 13) { + return num + "th"; + } + if (j === 1) return num + "st"; + if (j === 2) return num + "nd"; + if (j === 3) return num + "rd"; + return num + "th"; } -module.exports = getOrdinalNumber; \ No newline at end of file +module.exports = getOrdinalNumber; diff --git a/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.test.js b/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.test.js index 6d55dfbb4..ec2f4c4ed 100644 --- a/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.test.js +++ b/Sprint-3/3-mandatory-practice/implement/get-ordinal-number.test.js @@ -1,13 +1,62 @@ const getOrdinalNumber = require("./get-ordinal-number"); -// In this week's prep, we started implementing getOrdinalNumber +// In this week's prep, we started implementing getOrdinalNumber // continue testing and implementing getOrdinalNumber for additional cases // Write your tests using Jest - remember to run your tests often for continual feedback // Case 1: Identify the ordinal number for 1 // When the number is 1, // Then the function should return "1st" - test("should return '1st' for 1", () => { - expect(getOrdinalNumber(1)).toEqual("1st"); - }); + expect(getOrdinalNumber(1)).toEqual("1st"); +}); + +// Case 2: Identify the ordinal number for 2 +test("should return '2nd' for 2", () => { + expect(getOrdinalNumber(2)).toEqual("2nd"); +}); + +// Case 3: Identify the ordinal number for 3 +test("should return '3rd' for 3", () => { + expect(getOrdinalNumber(3)).toEqual("3rd"); +}); + +// Case 4: Identify the ordinal number for 4 +test("should return '4th' for 4", () => { + expect(getOrdinalNumber(4)).toEqual("4th"); +}); + +// Case 5: Identify the ordinal number for 11 (special teen case) +test("should return '11th' for 11", () => { + expect(getOrdinalNumber(11)).toEqual("11th"); +}); + +// Case 6: Identify the ordinal number for 12 (special teen case) +test("should return '12th' for 12", () => { + expect(getOrdinalNumber(12)).toEqual("12th"); +}); + +// Case 7: Identify the ordinal number for 13 (special teen case) +test("should return '13th' for 13", () => { + expect(getOrdinalNumber(13)).toEqual("13th"); +}); + +// Case 8: Identify the ordinal number for 21 +test("should return '21st' for 21", () => { + expect(getOrdinalNumber(21)).toEqual("21st"); +}); + +// Case 9: Identify the ordinal number for 22 +test("should return '22nd' for 22", () => { + expect(getOrdinalNumber(22)).toEqual("22nd"); +}); + +// Case 10: Identify the ordinal number for 23 +test("should return '23rd' for 23", () => { + expect(getOrdinalNumber(23)).toEqual("23rd"); +}); + +// Case 11: Identify the ordinal number for 101 +test("should return '101st' for 101", () => { + expect(getOrdinalNumber(101)).toEqual("101st"); +}); diff --git a/Sprint-3/3-mandatory-practice/implement/repeat.js b/Sprint-3/3-mandatory-practice/implement/repeat.js index 621f9bd35..1e23c8339 100644 --- a/Sprint-3/3-mandatory-practice/implement/repeat.js +++ b/Sprint-3/3-mandatory-practice/implement/repeat.js @@ -1,5 +1,9 @@ -function repeat() { - return "hellohellohello"; +// Implement a function repeat +function repeat(str, count) { + if (count < 0) { + throw new Error("Invalid count"); // выбрасываем ошибку для отрицательного count + } + return str.repeat(count); // встроенный метод повторяет строку count раз } -module.exports = repeat; \ No newline at end of file +module.exports = repeat; // правильно экспортируем функцию diff --git a/Sprint-3/3-mandatory-practice/implement/repeat.test.js b/Sprint-3/3-mandatory-practice/implement/repeat.test.js index 8a4ab42ef..a2566a341 100644 --- a/Sprint-3/3-mandatory-practice/implement/repeat.test.js +++ b/Sprint-3/3-mandatory-practice/implement/repeat.test.js @@ -1,32 +1,32 @@ -// Implement a function repeat -const repeat = require("./repeat"); -// Given a target string str and a positive integer count, -// When the repeat function is called with these inputs, -// Then it should: - -// case: repeat String: -// Given a target string str and a positive integer count, -// When the repeat function is called with these inputs, -// Then it should repeat the str count times and return a new string containing the repeated str values. +const repeat = require("./repeat"); // импортируем правильно +// Scenario: Repeat String test("should repeat the string count times", () => { - const str = "hello"; - const count = 3; - const repeatedStr = repeat(str, count); - expect(repeatedStr).toEqual("hellohellohello"); - }); + const str = "hello"; + const count = 3; + const repeatedStr = repeat(str, count); + expect(repeatedStr).toEqual("hellohellohello"); +}); -// case: handle Count of 1: -// Given a target string str and a count equal to 1, -// When the repeat function is called with these inputs, -// Then it should return the original str without repetition, ensuring that a count of 1 results in no repetition. +// Scenario: Handle count of 1 +test("should return the original string if count is 1", () => { + const str = "hello"; + const count = 1; + const repeatedStr = repeat(str, count); + expect(repeatedStr).toEqual("hello"); +}); -// case: Handle Count of 0: -// Given a target string str and a count equal to 0, -// When the repeat function is called with these inputs, -// Then it should return an empty string, ensuring that a count of 0 results in an empty output. +// Scenario: Handle count of 0 +test("should return an empty string if count is 0", () => { + const str = "hello"; + const count = 0; + const repeatedStr = repeat(str, count); + expect(repeatedStr).toEqual(""); +}); -// case: Negative Count: -// 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. +// Scenario: Negative count +test("should throw an error if count is negative", () => { + const str = "hello"; + const count = -2; + expect(() => repeat(str, count)).toThrow("Invalid count"); +}); diff --git a/Sprint-3/4-stretch-investigate/find.js b/Sprint-3/4-stretch-investigate/find.js index c7e79a2f2..7de3eaea3 100644 --- a/Sprint-3/4-stretch-investigate/find.js +++ b/Sprint-3/4-stretch-investigate/find.js @@ -2,11 +2,24 @@ function find(str, char) { let index = 0; while (index < str.length) { + // a) How the index variable updates during the call to find: + // The index variable starts at 0 and increases by 1 on each iteration of the loop. + // This allows checking each character of the string in order. + if (str[index] === char) { + // b) What is the if statement used to check: + // It checks whether the current character in the string matches the searched character (char). return index; } + index++; + // c) Why is index++ being used? + // index++ increments the index by 1 so that the loop can move to the next character in the string. } + + // d) What is the condition index < str.length used for? + // This condition ensures that the loop does not go beyond the string length. + // When index equals the string length, the loop stops. return -1; } diff --git a/Sprint-3/4-stretch-investigate/password-validator.js b/Sprint-3/4-stretch-investigate/password-validator.js index b55d527db..db00b76e6 100644 --- a/Sprint-3/4-stretch-investigate/password-validator.js +++ b/Sprint-3/4-stretch-investigate/password-validator.js @@ -1,6 +1,30 @@ +// Validate passwords according to the following rules: +// - Minimum length: 5 +// - At least one uppercase letter +// - At least one lowercase letter +// - At least one number +// - At least one special character from ! # $ % . * & + function passwordValidator(password) { - return password.length < 5 ? false : true -} + if (typeof password !== "string") return false; + + // Check minimum length + if (password.length < 5) return false; + + // Check for uppercase letter + if (!/[A-Z]/.test(password)) return false; + // Check for lowercase letter + if (!/[a-z]/.test(password)) return false; + + // Check for digit + if (!/[0-9]/.test(password)) return false; + + // Check for special character + if (!/[!#$%.*&]/.test(password)) return false; + + // All rules passed + return true; +} -module.exports = passwordValidator; \ No newline at end of file +module.exports = passwordValidator; diff --git a/Sprint-3/4-stretch-investigate/password-validator.test.js b/Sprint-3/4-stretch-investigate/password-validator.test.js index 8fa3089d6..3b29ec13e 100644 --- a/Sprint-3/4-stretch-investigate/password-validator.test.js +++ b/Sprint-3/4-stretch-investigate/password-validator.test.js @@ -1,26 +1,32 @@ -/* -Password Validation +const passwordValidator = require("./password-validator"); -Write a program that should check if a password is valid -and returns a boolean +// Test: minimum length +test("password has at least 5 characters", () => { + expect(passwordValidator("12345")).toBe(false); // no letters, no special char + expect(passwordValidator("Ab1!2")).toBe(true); + expect(passwordValidator("Ab1!")).toBe(false); +}); -To be valid, a password must: -- Have at least 5 characters. -- Have at least one English uppercase letter (A-Z) -- Have at least one English lowercase letter (a-z) -- Have at least one number (0-9) -- Have at least one of the following non-alphanumeric symbols: ("!", "#", "$", "%", ".", "*", "&") -- Must not be any previous password in the passwords array. +// Test: at least one uppercase letter +test("password has at least one uppercase letter", () => { + expect(passwordValidator("abcdef1!")).toBe(false); + expect(passwordValidator("Abcdef1!")).toBe(true); +}); -You must breakdown this problem in order to solve it. Find one test case first and get that working -*/ -const isValidPassword = require("./password-validator"); -test("password has at least 5 characters", () => { - // Arrange - const password = "12345"; - // Act - const result = isValidPassword(password); - // Assert - expect(result).toEqual(true); -} -); \ No newline at end of file +// Test: at least one lowercase letter +test("password has at least one lowercase letter", () => { + expect(passwordValidator("ABCDEF1!")).toBe(false); + expect(passwordValidator("ABCDEf1!")).toBe(true); +}); + +// Test: at least one number +test("password has at least one number", () => { + expect(passwordValidator("Abcdef!")).toBe(false); + expect(passwordValidator("Abcde1!")).toBe(true); +}); + +// Test: at least one special character +test("password has at least one special character (!, #, $, %, ., *, &)", () => { + expect(passwordValidator("Abcde12")).toBe(false); + expect(passwordValidator("Abcde1!")).toBe(true); +}); diff --git a/Sprint-3/card-validator.js b/Sprint-3/card-validator.js new file mode 100644 index 000000000..4bdcb4c3b --- /dev/null +++ b/Sprint-3/card-validator.js @@ -0,0 +1,18 @@ +function validateCreditCard(number) { + // Проверяем, что длина 16 и все символы — цифры + if (!/^\d{16}$/.test(number)) return false; + + // Проверяем, что есть хотя бы две разные цифры + if (new Set(number).size < 2) return false; + + // Проверяем, что последняя цифра чётная + if (parseInt(number[15]) % 2 !== 0) return false; + + // Проверяем, что сумма всех цифр больше 16 + const sum = number.split("").reduce((acc, n) => acc + Number(n), 0); + if (sum <= 16) return false; + + return true; // карта валидная +} + +module.exports = validateCreditCard; diff --git a/Sprint-3/card-validator.test.js b/Sprint-3/card-validator.test.js new file mode 100644 index 000000000..78b2f9494 --- /dev/null +++ b/Sprint-3/card-validator.test.js @@ -0,0 +1,21 @@ +const validateCreditCard = require("./card-validator"); + +test("valid credit card 9999777788880000", () => { + expect(validateCreditCard("9999777788880000")).toBe(true); +}); + +test("invalid: all same digits", () => { + expect(validateCreditCard("4444444444444444")).toBe(false); +}); + +test("invalid: last digit odd", () => { + expect(validateCreditCard("6666666666666661")).toBe(false); +}); + +test("invalid: sum < 16", () => { + expect(validateCreditCard("1111111111111110")).toBe(false); +}); + +test("invalid: contains non-numbers", () => { + expect(validateCreditCard("a92332119c011112")).toBe(false); +});