diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js index 653d6f5a0..e8e4c9dd4 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -1,13 +1,25 @@ // Predict and explain first... // =============> write your prediction here +/* The function capitalise() is trying to return the first letter of a string capitalised. However our program will +fail because it's declaring a variable inside a function using the same name as the parameter that is passed to the function. +If I attempt to run the program, It will generate a SyntaxError stating that 'str' has already been declared. + +*/ // call the function capitalise with a string input // interpret the error message and figure out why an error is occurring +// - The error is a SyntaxError stating that 'str' has already been declared. -function capitalise(str) { - let str = `${str[0].toUpperCase()}${str.slice(1)}`; - return str; -} +// function capitalise(str) { +// let str = `${str[0].toUpperCase()}${str.slice(1)}`; +// return str; +// } // =============> write your explanation here +// To solve the Error, we can either store the string interpolation with a different variable name or we can return the string interpolation if we don't intend to reuse it. + // =============> write your new code here +function capitalise(str) { + let strCaps = `${str[0].toUpperCase()}${str.slice(1)}`; + return strCaps; +} diff --git a/Sprint-2/1-key-errors/1.js b/Sprint-2/1-key-errors/1.js index f2d56151f..310ac7372 100644 --- a/Sprint-2/1-key-errors/1.js +++ b/Sprint-2/1-key-errors/1.js @@ -1,20 +1,38 @@ // Predict and explain first... +/*The function below is trying to convert a decimal number to percentage */ // Why will an error occur when this program runs? // =============> write your prediction here - +/*An error will occur because the program logs the parameter decimalNumber instead 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 function convertToPercentage() takes a parameter called decimalNumber +- it's declaring a constant variable with the parameter decimalNumber which will throw an error because it's withing the same scope and in JS is not allowed. Variable names suppose to be unique within the same scope. +- It's storing a hardcoded value of 0.5 as value to the constant variable decimalNumber +- It creates a constant variable percentage to store the value of multiplying decimalNumber by 100 to get the percentage +- It returns percentage +- Finally, it logs the parameter decimalNumber without the function which will generate an error. +*/ // Finally, correct the code to fix the problem // =============> write your new code here + +function convertToPercentage(decimalNumber) { + const decimalNumberValue = decimalNumber; + const percentage = `${decimalNumberValue * 100}%`; + + return percentage; +} + +console.log(convertToPercentage(0.8)); diff --git a/Sprint-2/1-key-errors/2.js b/Sprint-2/1-key-errors/2.js index aad57f7cf..ea1cc8426 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -5,16 +5,35 @@ // =============> write your prediction of the error here -function square(3) { - return num * num; -} +// function square(3) { +// return num * num; +// } // =============> write the error message here +/*/Users/ike/CYF/Module-Structuring-and-Testing-Data/Sprint-2/1-key-errors/2.js:8 +function square(3) { + ^ +SyntaxError: Unexpected number + at wrapSafe (internal/modules/cjs/loader.js:979:16) + at Module._compile (internal/modules/cjs/loader.js:1027:27) + at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10) + at Module.load (internal/modules/cjs/loader.js:928:32) + at Function.Module._load (internal/modules/cjs/loader.js:769:14) + at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) + at internal/main/run_main_module.js:17:47 +*/ // =============> explain this error message here +/* +- the error is a SyntaxError because we are passing the parameter 3 to the function and our program isn't expecting a number. +_ To fix this error, we need to pass the variable num as parameter to the function square. +*/ // Finally, correct the code to fix the problem // =============> write your new code here +function square(num) { + return num * num; +} - +console.log(square(3)) diff --git a/Sprint-2/2-mandatory-debug/0.js b/Sprint-2/2-mandatory-debug/0.js index b27511b41..cec6e83a4 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -1,14 +1,23 @@ // Predict and explain first... // =============> write your prediction here +/* +- The function multiply takes 2 parameters a and b and logging the value of a multiplied by b within the function but it's not returning the value. -function multiply(a, b) { - console.log(a * b); -} +*/ +// function multiply(a, b) { +// console.log(a * b); +// } -console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); +// console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); // =============> write your explanation here - +// - Line 9 will log the value to the console but line 12 will generate undefined because the value of a * b is not returned. // Finally, correct the code to fix the problem // =============> write your new code here + +function multiply(a, b) { + return (a * b); +} + +console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`); diff --git a/Sprint-2/2-mandatory-debug/1.js b/Sprint-2/2-mandatory-debug/1.js index 37cedfbcf..3fe79fe6a 100644 --- a/Sprint-2/2-mandatory-debug/1.js +++ b/Sprint-2/2-mandatory-debug/1.js @@ -1,13 +1,18 @@ // Predict and explain first... // =============> write your prediction here +// - The function will print undefined as it's not returning anything. -function sum(a, b) { - return; - a + b; -} +// function sum(a, b) { +// return; +// a + b; +// } -console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); +// console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); // =============> write your explanation here // Finally, correct the code to fix the problem // =============> write your new code here +function sum(a, b) { + return a + b;; +} +console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); diff --git a/Sprint-2/2-mandatory-debug/2.js b/Sprint-2/2-mandatory-debug/2.js index 57d3f5dc3..31cff9b71 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -2,16 +2,17 @@ // Predict the output of the following code: // =============> Write your prediction here +// This function getLastDigit is trying to get the last digit of a number but will not work because it has no parameter -const num = 103; +// const num = 103; -function getLastDigit() { - return num.toString().slice(-1); -} +// function getLastDigit() { +// return num.toString().slice(-1); +// } -console.log(`The last digit of 42 is ${getLastDigit(42)}`); -console.log(`The last digit of 105 is ${getLastDigit(105)}`); -console.log(`The last digit of 806 is ${getLastDigit(806)}`); +// console.log(`The last digit of 42 is ${getLastDigit(42)}`); +// console.log(`The last digit of 105 is ${getLastDigit(105)}`); +// console.log(`The last digit of 806 is ${getLastDigit(806)}`); // Now run the code and compare the output to your prediction // =============> write the output here @@ -20,5 +21,17 @@ console.log(`The last digit of 806 is ${getLastDigit(806)}`); // Finally, correct the code to fix the problem // =============> write your new code here +const num = 103; + +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 + +/* This function getLastDigit is trying to get the last digit of a number but will not work because it has no parameter. It instead declares the variable globally and the function will reference it as argument when we call the function because it was declared globally. This will print 3 for each call +*/ diff --git a/Sprint-2/3-mandatory-implement/1-bmi.js b/Sprint-2/3-mandatory-implement/1-bmi.js index 17b1cbde1..89d2ef1de 100644 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -16,4 +16,10 @@ function calculateBMI(weight, height) { // return the BMI of someone based off their weight and height -} \ No newline at end of file + let heightSquared = height * height; + let bmiInDecimals = weight/ heightSquared; + let bmi = bmiInDecimals.toFixed(1); + return bmi +} + +// console.log(calculateBMI(102, 1.85)); diff --git a/Sprint-2/3-mandatory-implement/2-cases.js b/Sprint-2/3-mandatory-implement/2-cases.js index 5b0ef77ad..99d22165c 100644 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -14,3 +14,13 @@ // 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 + +// create a function called upperSnakeCase that takes a string of 2 or more words as a parameter +//returns the string in upper snake case e.g "hello ike" = HELLO_IKE + +function upperSnakeCase(str){ + let capitalizedSnakeCase = str.toUpperCase().replaceAll(" ","_"); + return capitalizedSnakeCase +} + + diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js index 6265a1a70..a5ceb46f5 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -4,3 +4,27 @@ // 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 toPound(penceDigits) { + //initialises a constant variable with the value penceDigits + const penceString = penceDigits; + // removes the last element from the string using subString() + const penceStringWithoutTrailingP = penceString.substring( + 0, + penceString.length - 1 + ); + //returns 399 because the targetLength 3 is equivalent to the length of the string. So no "0" padding will be added. + const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); + //removing the last 2 digit of 399 + const pounds = paddedPenceNumberString.substring( + 0, + paddedPenceNumberString.length - 2 + ); + // returns 99 given that the padding starts at end and it's length is 2. + const pence = paddedPenceNumberString + .substring(paddedPenceNumberString.length - 2) + .padEnd(2, "0"); + //returns the value of pound and pence. Appends the £ at the start. + return `£${pounds}.${pence}`; +} + diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js index 7c98eb0e8..6a339e6ca 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -3,14 +3,16 @@ function pad(num) { } function formatTimeDisplay(seconds) { - const remainingSeconds = seconds % 60; - const totalMinutes = (seconds - remainingSeconds) / 60; - const remainingMinutes = totalMinutes % 60; - const totalHours = (totalMinutes - remainingMinutes) / 60; + const remainingSeconds = seconds % 60; //61 % 60 = 1 + const totalMinutes = (seconds - remainingSeconds) / 60; //(61-1)/60 = 1 + const remainingMinutes = totalMinutes % 60; //1 % 60 = 1 + const totalHours = (totalMinutes - remainingMinutes) / 60; //(1 - 1)/60 = 0 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,22 @@ function formatTimeDisplay(seconds) { // a) When formatTimeDisplay is called how many times will pad be called? // =============> write your answer here +// pad will be called 3 times // Call formatTimeDisplay with an input of 61, now answer the following: // b) What is the value assigned to num when pad is called for the first time? // =============> write your answer here +// The value is 0 because total hours is 0 i.e (1-1)/60 = 0 // c) What is the return value of pad is called for the first time? // =============> write your answer here +// The return value is 00 because "0".padStart(2, "0") is "00" // d) What is the value assigned to num when pad is called for the last time in this program? Explain your answer // =============> write your answer here +// the value is 1 because 61 % 60 = 1 // 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 +// The return value is 01 because the value assign to nun is 1. When pad is called, it adds 0 at the start of the num because the length of the string num is currently 1. 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..b84d029c1 100644 --- a/Sprint-3/1-key-implement/1-get-angle-type.js +++ b/Sprint-3/1-key-implement/1-get-angle-type.js @@ -10,6 +10,10 @@ 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 "Acute angle"; + if(angle > 90 && angle < 180) return "Obtuse angle"; + if (angle === 180) return "Straight angle"; + if(angle > 180 && angle < 360) return "Reflex angle"; } // we're going to use this helper function to make our assertions easier to read @@ -41,16 +45,20 @@ assertEquals(acute, "Acute angle"); // Case 3: Identify Obtuse Angles: // When the angle is greater than 90 degrees and less than 180 degrees, +// if(angle > 90 && angle is < 180) return "Obtuse angle" // 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 +// ====> write your test here, and then add a line to pass the test in the function above +const reflex = getAngleType(360) +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..86c2d182e 100644 --- a/Sprint-3/1-key-implement/2-is-proper-fraction.js +++ b/Sprint-3/1-key-implement/2-is-proper-fraction.js @@ -9,6 +9,7 @@ function isProperFraction(numerator, denominator) { if (numerator < denominator) return true; + if (numerator >= denominator) return false; } // here's our helper again @@ -41,6 +42,7 @@ assertEquals(improperFraction, false); // 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 @@ -48,6 +50,7 @@ const negativeFraction = isProperFraction(-4, 7); // 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? 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..553c0aa76 100644 --- a/Sprint-3/1-key-implement/3-get-card-value.js +++ b/Sprint-3/1-key-implement/3-get-card-value.js @@ -7,8 +7,19 @@ // 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; + let rank = card.slice(0,-1); // this line removes the emojis + + if (rank === "A") { + return 11; + } else if (+rank >= 2 && +rank <= 10) { + return +rank; + } else if (rank === "J" || rank === "Q" || rank === "K"){ + return 10; + } else { + return "Invalid Card rank."; + } } // You need to write assertions for your function to check it works in different cases @@ -34,12 +45,26 @@ assertEquals(aceofSpades, 11); // Then it should return the numeric value corresponding to the rank (e.g., "5" should return 5). const fiveofHearts = getCardValue("5♥"); // ====> write your test here, and then add a line to pass the test in the function above +assertEquals(fiveofHearts, 5); // 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. +const rankTen = getCardValue("10♥"); +assertEquals(rankTen, 10); + +const cardK = getCardValue("K♠"); +assertEquals(cardK, 10); + +const cardJ = getCardValue("J♣"); +assertEquals(cardJ, 10); + +const cardQ = getCardValue("Q♦"); +assertEquals(cardQ, 10) + + // Handle Ace (A): // Given a card with a rank of "A", // When the function is called with an Ace, @@ -49,3 +74,5 @@ const fiveofHearts = getCardValue("5♥"); // 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." +const invalidCards = getCardValue(""); +assertEquals(invalidCards, "Invalid Card rank."); 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..a4d4e2bf1 100644 --- a/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js +++ b/Sprint-3/2-mandatory-rewrite/1-get-angle-type.js @@ -1,7 +1,10 @@ function getAngleType(angle) { if (angle === 90) return "Right angle"; // replace with your completed function from key-implement - + if (angle < 90) return "Acute angle"; + if (angle > 90 && angle < 180) return "Obtuse angle"; + if (angle === 180) return "Straight angle"; + if (angle > 180 && angle < 360) return "Reflex angle"; } @@ -13,6 +16,6 @@ function getAngleType(angle) { // 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 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..d61f0bde0 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 @@ -11,14 +11,28 @@ test("should identify right angle (90°)", () => { // When the angle is less than 90 degrees, // Then the function should return "Acute angle" +test("should identify Acute angle when Angle is less than 90°", ()=>{ + expect(getAngleType(80)).toEqual("Acute angle"); +}); + // 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 when Angle is greater than 90° and less thank 180°", () => { + expect(getAngleType(101)).toEqual("Obtuse angle"); +}); // Case 4: Identify Straight Angles: // When the angle is exactly 180 degrees, // Then the function should return "Straight angle" +test("should identify Straight angle when Angle is 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, // Then the function should return "Reflex angle" + +test("should identify Reflex angle when Angle is greater than 180° and less than 360°", () => { + expect(getAngleType(202)).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..e7f533e73 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 + if (numerator >= denominator) return false; } -module.exports = isProperFraction; \ No newline at end of file +module.exports = isProperFraction; 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..de3ef95e4 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,14 @@ 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 is Equal to 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..51eb17563 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,15 @@ function getCardValue(card) { // replace with your code from key-implement - return 11; + let rank = card.slice(0, -1); // this line removes the emojis + + if (rank === "A") { + return 11; + } else if (+rank >= 2 && +rank <= 10) { + return +rank; + } else if (rank === "J" || rank === "Q" || rank === "K") { + return 10; + } else { + return "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..00b187658 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,23 @@ const getCardValue = require("./3-get-card-value"); test("should return 11 for Ace of Spades", () => { - const aceofSpades = getCardValue("A♠"); - expect(aceofSpades).toEqual(11); + expect(getCardValue("A♠")).toEqual(11); }); // Case 2: Handle Number Cards (2-10): +test("Should return rank number between 2 and 10",()=>{ + expect(getCardValue("5♥")).toEqual(5); +}); + // Case 3: Handle Face Cards (J, Q, K): +test("Should return 10 for Face Cards J, Q, K", () => { +expect(getCardValue("K♠")).toEqual(10); +expect(getCardValue("J♣")).toEqual(10); +expect(getCardValue("Q♦")).toEqual(10); +}); + // Case 4: Handle Ace (A): // Case 5: Handle Invalid Cards: +test("should throw an error indicating Invalid card rank.", () => { + expect(getCardValue("")).toEqual("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..0bb5988aa 100644 --- a/Sprint-3/3-mandatory-practice/implement/count.js +++ b/Sprint-3/3-mandatory-practice/implement/count.js @@ -1,5 +1,12 @@ -function countChar(stringOfCharacters, findCharacter) { - return 5 +function countChar(strOfCahracters, findcharacter) { + let count = 0; + for (let i = 0; i < strOfCahracters.length; i++) { + if (strOfCahracters[i] === findcharacter) { + count++; + } + } + return count; } -module.exports = countChar; \ No newline at end of file +// console.log(countChar("aaaaa", "a")); +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..70d755578 100644 --- a/Sprint-3/3-mandatory-practice/implement/count.test.js +++ b/Sprint-3/3-mandatory-practice/implement/count.test.js @@ -22,3 +22,10 @@ test("should count multiple occurrences of a character", () => { // 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 identify no occurrences of character", () => { + const str1 = 'AAAAA' + const char1 = 'a' + const count = countChar(str1, char1) + expect(count).toEqual(0); +}); 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..4c2b214be 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,22 @@ function getOrdinalNumber(num) { - return "1st"; + let lastNumber = num % 10; // Using the modulo operator to get the last digit of the number. + let lastTwoNumbers = num % 100; //Using the modulo operator to get the last two digits of the number. + + if (lastTwoNumbers === 11 || lastTwoNumbers === 12 || lastTwoNumbers === 13) { + return num + "th"; + } + + if (lastNumber === 1) { + return num + "st"; + } else if (lastNumber === 2) { + return num + "nd"; + } else if (lastNumber === 3) { + return num + "rd"; + } else { + return num + "th"; + } } -module.exports = getOrdinalNumber; \ No newline at end of file +console.log(getOrdinalNumber(3)); + +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..0362e871f 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 @@ -10,4 +10,23 @@ const getOrdinalNumber = require("./get-ordinal-number"); test("should return '1st' for 1", () => { expect(getOrdinalNumber(1)).toEqual("1st"); - }); + }); + +test("Should return '2nd' for 2",()=>{ + expect(getOrdinalNumber(2)).toEqual("2nd"); +}) + +test("Should return '3rd' for 3",()=>{ + expect(getOrdinalNumber(3)).toEqual("3rd"); +}) + +test("Should return '11th' for 11",()=>{ + expect(getOrdinalNumber(11)).toEqual("11th"); +}) +test("Should return '12th' for 12",()=>{ + expect(getOrdinalNumber(12)).toEqual("12th"); +}) + +test("Should return '13th' for 13",()=>{ + expect(getOrdinalNumber(13)).toEqual("13th"); +}) diff --git a/Sprint-3/3-mandatory-practice/implement/repeat.js b/Sprint-3/3-mandatory-practice/implement/repeat.js index 621f9bd35..71cf26eab 100644 --- a/Sprint-3/3-mandatory-practice/implement/repeat.js +++ b/Sprint-3/3-mandatory-practice/implement/repeat.js @@ -1,5 +1,10 @@ -function repeat() { - return "hellohellohello"; +function repeat(str, count) { + if (count < 0) { + return "Negative numbers are not valid!"; + } else { + return str.repeat(count); + } } -module.exports = repeat; \ No newline at end of file +console.log(repeat("hello", 10)); +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..fc7fdd993 100644 --- a/Sprint-3/3-mandatory-practice/implement/repeat.test.js +++ b/Sprint-3/3-mandatory-practice/implement/repeat.test.js @@ -21,12 +21,34 @@ test("should repeat the string count times", () => { // 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. +test("should return original string without repetition",()=>{ + const str = "country" + const count = 1 + const noRepetition = repeat(str, count) + expect(noRepetition).toEqual("country"); +}); + // 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. +test("should return an empty string count 0 should result to an empty output", () => { + const str = "country"; + const count = 0; + const emptyStr = repeat(str, count); + expect(emptyStr).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. + +test("should return an error message", () => { + const str = "hello" + const count = -2 + const errorMessage = repeat(str, count) + expect(errorMessage).toEqual("Negative numbers are not valid!"); +}); diff --git a/Sprint-3/4-stretch-investigate/card-validator.js b/Sprint-3/4-stretch-investigate/card-validator.js new file mode 100644 index 000000000..ce8f82ddd --- /dev/null +++ b/Sprint-3/4-stretch-investigate/card-validator.js @@ -0,0 +1,33 @@ + +function creditCardValidator(cardNumber) { + let cardNumberArray = cardNumber.split(""); // convert to array of strings + let intNumber = cardNumberArray.map((num) => +num); // convert array of strings to array integers + let sum = 0; + let regexNum = /^[0-9]+$/; + + if (!regexNum.test(cardNumber)) return "Invalid Characters."; //check if cardNumber contains any letter or special character + + for (let i = 0; i < intNumber.length; i++) { + sum += intNumber[i]; + } + + if (cardNumber[cardNumber.length - 1] % 2 == 1) + return "Invalid card: odd final number"; + + if (sum < 16) return "Sum less than 16 "; + + if (cardNumber.length === 16) return "Valid card"; + + // for(let i = 0; i < cardNumber.length; i++){ + // if(cardNumber[i] === cardNumber[1]) return "Invalid card: Only one type of number provided"; + // } + + return sum; +} + +console.log(creditCardValidator("9999777788880000"));//valid card number +console.log(creditCardValidator("6666666666661666"));//Valid card number +console.log(creditCardValidator("a92332119c011112"));//invalid characters +console.log(creditCardValidator("1111111111111110"));//sum less than 16 +console.log(creditCardValidator("4444444444444444")); //should fail bc Only one type of number provided" +console.log(creditCardValidator("6666666666666661"));//odd final number diff --git a/Sprint-3/4-stretch-investigate/find.js b/Sprint-3/4-stretch-investigate/find.js index c7e79a2f2..96d04df2e 100644 --- a/Sprint-3/4-stretch-investigate/find.js +++ b/Sprint-3/4-stretch-investigate/find.js @@ -20,6 +20,10 @@ console.log(find("code your future", "z")); // Pay particular attention to the following: // a) How the index variable updates during the call to find -// b) What is the if statement used to check +// - [It increases by 1 each time the while loop iterate.] +// b) What is the if statement used to check ? +// - [the if statement is checking that the current character matches the targeted character.] // c) Why is index++ being used? +// - [it is used so that the while loop will increment by 1 each time it loops] // d) What is the condition index < str.length used for? +// - [it's used as the condition to ensure thw loop runs only while the index is less than the length of the string.] diff --git a/Sprint-3/4-stretch-investigate/password-validator.js b/Sprint-3/4-stretch-investigate/password-validator.js index b55d527db..56077172b 100644 --- a/Sprint-3/4-stretch-investigate/password-validator.js +++ b/Sprint-3/4-stretch-investigate/password-validator.js @@ -1,6 +1,29 @@ function passwordValidator(password) { - return password.length < 5 ? false : true + const passwords = ["PasswordAccess1!", "PasswordAccess2!", "PasswordAccess3!"]; + if (password.length < 5) { + return false; + } + if (passwords.includes(password)) { + return false; + } + if (!/[a-z]/.test(password)) { + return false; + } + if (!/[A-Z]/.test(password)) { + return false; + } + if (!/[0-9]/.test(password)) { + return false; + } + if (!/[!#$%\.\*&]/.test(password)) { + return false; + } + + return true; } +// console.log(passwordValidator("Password1!")); +// console.log(passwordValidator("P2!4")); +// console.log(passwordValidator("PasswordAccess1!")); -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..2ab9428d2 100644 --- a/Sprint-3/4-stretch-investigate/password-validator.test.js +++ b/Sprint-3/4-stretch-investigate/password-validator.test.js @@ -1,4 +1,4 @@ -/* +/* Password Validation Write a program that should check if a password is valid @@ -10,17 +10,49 @@ To be valid, a password must: - 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. +- Must not be any previous password in the passwords array. You must breakdown this problem in order to solve it. Find one test case first and get that working */ -const isValidPassword = require("./password-validator"); +const isValidPassword = require("./password-validator.js"); test("password has at least 5 characters", () => { // Arrange - const password = "12345"; + const password = "Abc1!"; // Act const result = isValidPassword(password); // Assert expect(result).toEqual(true); } -); \ No newline at end of file +); + +test("password has at least an English uppercase letter (A-Z)", () => { + const password = "Team1!"; + const result = isValidPassword(password); + expect(result).toEqual(true); +}); + + +test("password has at least an English lowercase letter(a-z)", () => { + const password = "Access1!"; + const result = isValidPassword(password); + expect(result).toEqual(true); +}); + + +test("password must have at least a number (0-9)", () => { + const password = "Happy1!"; + const result = isValidPassword(password); + expect(result).toEqual(true); +}); + +test("password must have at least one non-alphanumeric symbols: ('!', '#', '$', '%', '.', '*', '&')", () => { + const password = "Life1!"; + const result = isValidPassword(password); + expect(result).toEqual(true); +}); + +test("password must not be any previous password in the passwords array", ()=> { + const password = "PasswordAccess1!"; + const result = isValidPassword(password); + expect(result).toEqual(false); +});