diff --git a/.gitignore b/.gitignore index bde36e530..843c14f21 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ node_modules .DS_Store .vscode -**/.DS_Store \ No newline at end of file +**/.DS_Store +package-lock.json \ No newline at end of file diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js index 117bcb2b6..8528dad15 100644 --- a/Sprint-1/1-key-exercises/1-count.js +++ b/Sprint-1/1-key-exercises/1-count.js @@ -1,6 +1,12 @@ let count = 0; - +/* Incrementing by 1 the count value. */ +count = count + 1; +/* Check if count === 1. */ +console.log(count); +/* Incrementing by 1 the count value. */ count = count + 1; +/* Check if count === 2. */ +console.log(count); // 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 diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js index 47561f617..7c37fc92d 100644 --- a/Sprint-1/1-key-exercises/2-initials.js +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -4,8 +4,10 @@ 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 = ``; +/* So many ways to get the first char of a string ! */ +let initials = `${firstName.charAt(0)}${middleName[0]}${lastName.slice(0, 1)}`; +/* Check if ok */ +console.log(initials); // https://www.google.com/search?q=get+first+character+of+string+mdn diff --git a/Sprint-1/1-key-exercises/3-paths.js b/Sprint-1/1-key-exercises/3-paths.js index ab90ebb28..4167dfd2f 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -14,10 +14,15 @@ const lastSlashIndex = filePath.lastIndexOf("/"); const base = filePath.slice(lastSlashIndex + 1); 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 +// Create a variable to store the directories part of the filePath variable. +// Create a variable to store the extension part of the variable. -const dir = ; -const ext = ; +/* Funny ! */ +const dir = filePath.slice(0, lastSlashIndex + 1); +const lastPointIndex = filePath.lastIndexOf("."); +const ext = filePath.slice(lastPointIndex + 1); +/* Check */ +console.log("The directories part of the filePath is : " + dir); +console.log("The extension part of the variable is : " + ext); -// https://www.google.com/search?q=slice+mdn \ No newline at end of file +// https://www.google.com/search?q=slice+mdn diff --git a/Sprint-1/1-key-exercises/4-random.js b/Sprint-1/1-key-exercises/4-random.js index 292f83aab..8f393e825 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -1,7 +1,37 @@ const minimum = 1; const maximum = 100; +/* + * Well-known JavaScript pattern for generating random integers + * in a specific range [minimum, maximum] (both inclusive). + * minimum <= num <= maximum. + */ +/* Shift along the range from min to max. */ const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; +/* Check */ +let counter = 0; +const min = 5; +const max = 20; + +while (counter <= 5) { + console.log("\nMinimum", min, "Maximum", max); + // Mystery of Mathematics. + const m = max - min + 1; + console.log("(max - min + 1) => ", m); + /* return random float in between 0 and 1 (non inclusive) */ + const rd = Math.random(); + console.log("random", rd); + // Mystery of Mathematics. + console.log(`(${m} * random) => `, m * rd); + /* Math.floor return the nearest lower integer + * E.g. Math.floor(3.9) === 3; + * Return a range 0 => 99. + */ + const int = Math.floor(rd * m); + console.log(`Math.floor(${m} * random) =>`, int); + console.log(`${int} + ${min} =>`, Math.floor(rd * m) + min); + counter++; +} // In this exercise, you will need to work out what num represents? // Try breaking down the expression and using documentation to explain what it means diff --git a/Sprint-1/2-mandatory-errors/0.js b/Sprint-1/2-mandatory-errors/0.js index cf6c5039f..7f6de0f21 100644 --- a/Sprint-1/2-mandatory-errors/0.js +++ b/Sprint-1/2-mandatory-errors/0.js @@ -1,2 +1,5 @@ -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? */ +/* + * Just comment it. +*/ \ 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..4664a87d8 100644 --- a/Sprint-1/2-mandatory-errors/1.js +++ b/Sprint-1/2-mandatory-errors/1.js @@ -1,4 +1,7 @@ // trying to create an age variable and then reassign the value by 1 - -const age = 33; +/* TypeError: Assignment to constant variable. */ +// const age = 33; +let age = 33; age = age + 1; +/* Check if ok. */ +console.log(age); diff --git a/Sprint-1/2-mandatory-errors/2.js b/Sprint-1/2-mandatory-errors/2.js index e09b89831..c5ffaab65 100644 --- a/Sprint-1/2-mandatory-errors/2.js +++ b/Sprint-1/2-mandatory-errors/2.js @@ -1,5 +1,7 @@ // 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}`); +/* Cannot access 'cityOfBirth' before initialization */ +// const cityOfBirth = "Bolton"; diff --git a/Sprint-1/2-mandatory-errors/3.js b/Sprint-1/2-mandatory-errors/3.js index ec101884d..bfc078a47 100644 --- a/Sprint-1/2-mandatory-errors/3.js +++ b/Sprint-1/2-mandatory-errors/3.js @@ -1,5 +1,16 @@ const cardNumber = 4533787178994213; -const last4Digits = cardNumber.slice(-4); +/* cardNumber is a number but slice() is a String method. */ +/* TypeError: cardNumber.slice is not a function. */ +//const last4Digits = cardNumber.slice(-4); +const last4Digits = cardNumber.toString().slice(-4); +/* Another way to cast a number (string + number == string) */ +const otherLast4Digits = `${cardNumber}`.toString().slice(-4); +const anotherLast4Digits = ("" + cardNumber).slice(-4); +/* Check if ok */ +console.log(last4Digits); +console.log(otherLast4Digits); +console.log(anotherLast4Digits); + // 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..a183e3d7f 100644 --- a/Sprint-1/2-mandatory-errors/4.js +++ b/Sprint-1/2-mandatory-errors/4.js @@ -1,2 +1,9 @@ -const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; \ No newline at end of file +/* Js variables are not allowed to start with digit */ +/* SyntaxError: Invalid or unexpected token */ +// const 12HourClockTime = "20:53"; +// const 24hourClockTime = "08:53"; +const hourClockTime12 = "20:53"; +const hourClockTime24 = "08:53"; +/* Check if ok. */ +console.log("hourClockTime12 : " + hourClockTime12); +console.log("hourClockTime24 : " + hourClockTime24); \ No newline at end of file diff --git a/Sprint-1/3-mandatory-interpret/1-percentage-change.js b/Sprint-1/3-mandatory-interpret/1-percentage-change.js index e24ecb8e1..9ff524be8 100644 --- a/Sprint-1/3-mandatory-interpret/1-percentage-change.js +++ b/Sprint-1/3-mandatory-interpret/1-percentage-change.js @@ -2,21 +2,42 @@ 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; -console.log(`The percentage change is ${percentageChange}`); +console.log(`The percentage change is ${percentageChange} %`); // Read the code and then answer the questions below -// a) How many function calls are there in this file? Write down all the lines where a function call is made +// a) How many function calls are there in this file? +// Write down all the lines where a function call is made. +/* + * line 4 & 5 => replaceAll() - String method. + * line 4 & 5 => Number() - built-in constructor function + * line 10 => console.log() - built-in constructor function +*/ -// b) Run the code and identify the line where the error is coming from - why is this error occurring? How can you fix this problem? +// b) Run the code and identify the line where the error is coming from +// why is this error occurring? How can you fix this problem? +/* + * line 5 => Miss a comma in arguments declaration. +*/ // c) Identify all the lines that are variable reassignment statements +/* + * lines 4 & 5 => carPrice & priceAfterOneYear are reassigned. +*/ // d) Identify all the lines that are variable declarations - -// e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? +/* + * lines 1 & 2 => carPrice & priceAfterOneYear. + * lines 7 & 8 => priceDifference & percentageChange. +*/ + +// e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing +// what is the purpose of this expression? +/* + * Cast a string to Number. +*/ diff --git a/Sprint-1/3-mandatory-interpret/2-time-format.js b/Sprint-1/3-mandatory-interpret/2-time-format.js index 47d239558..8a49dd562 100644 --- a/Sprint-1/3-mandatory-interpret/2-time-format.js +++ b/Sprint-1/3-mandatory-interpret/2-time-format.js @@ -1,4 +1,4 @@ -const movieLength = 8784; // length of movie in seconds +const movieLength = -8784; // length of movie in seconds const remainingSeconds = movieLength % 60; const totalMinutes = (movieLength - remainingSeconds) / 60; @@ -12,14 +12,40 @@ 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? +/* + * 6 variable's declarations: + * movieLength, remainingSeconds, totalMinutes, remainingMinutes, totalHours, result. +*/ // b) How many function calls are there? +/* + * Only console.log() +*/ // c) Using documentation, explain what the expression movieLength % 60 represents // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators +/* + * Modulo (%) is use to return the rest number of a division. + * 8784 % 60 = 8784 - (60 × Math.floor(8784 / 60)); +*/ +console.log( "\nModule explained"); +console.log("8784 % 60 =" ,8784 - (60 * Math.floor(8784 / 60))); -// d) Interpret line 4, what does the expression assigned to totalMinutes mean? - -// 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 +// d) Interpret line 4, what does the expression assigned to totalMinutes mean? +/* + * The rest number are the seconds. + * We substract them to the time length then timelength / 60 result + * is minutes (60 seconds in a minute). +*/ + +// e) What do you think the variable result represents? +// Can you think of a better name for this variable? + /* getClockTime() */ + +// f) Try experimenting with different values of movieLength. +// Will this code work for all values of movieLength? Explain your answer +/* + * Yes but the result display is not optimal in case + * movieLength = 0 ormovieLength < 0 or totalHours === 0 or some of the value < 10. +*/ diff --git a/Sprint-1/3-mandatory-interpret/3-to-pounds.js b/Sprint-1/3-mandatory-interpret/3-to-pounds.js index 60c9ace69..93a000874 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -10,6 +10,8 @@ const pounds = paddedPenceNumberString.substring( 0, paddedPenceNumberString.length - 2 ); +console.log(paddedPenceNumberString.charAt(0)); + const pence = paddedPenceNumberString .substring(paddedPenceNumberString.length - 2) @@ -25,3 +27,34 @@ 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( penceString.length - 1); + * Assign the penceStringWithoutTrailingP variable to string penceString trailing last char of it. + * length of penceString - 1 because index begins to 0 + * String method substring() parameter does not accept negative index (unlike slice) + * String method substring() returns charAt(3) to the end. + * penceString is not muted (remains the same). + * + * 3. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); + * penceStringWithoutTrailingP.padStart(3, "0") = add (number - string.length) "0" + * Here penceStringWithoutTrailingP.length = 3 so 3 - 3 = nothing to add. + * useful to add 0 if the price < 1 pound (Impossible nowadays). + + * 4. const pounds = paddedPenceNumberString.substring( 0, paddedPenceNumberString.length - 2); + * String method substring() returns charAt(0) to charAt(1)(3- 1) non inclusif, + * Equivalent to substring( 0, 1); + * Equivalent to paddedPenceNumberString.charAt(0); + + * 5. const pence = paddedPenceNumberString + .substring(paddedPenceNumberString.length - 2) + .padEnd(2, "0"); + * String method substring() returns the 2 last char of the string. + * Here the pences. + * padEnd(2, "0") same system than above but add "0" at the end if the string.length < 2 + * E.g. "9" => "90". + + * 6. console.log(`£${pounds}.${pence}`); + * Display in the console currency + pound's value + separator + pence's value + * thanks to the template literals ``. + +*/ diff --git a/Sprint-1/4-stretch-explore/objects.md b/Sprint-1/4-stretch-explore/objects.md index 0216dee56..8c01bf619 100644 --- a/Sprint-1/4-stretch-explore/objects.md +++ b/Sprint-1/4-stretch-explore/objects.md @@ -14,3 +14,7 @@ Answer the following questions: What does `console` store? What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? +- console.log(["message"], value.toString()) +- console.assert(assertion, "message", [optionalParams]); +- - assertion returns a boolean (false / true). If false the message will be displayed in the console. +- - E.g. console.assert(5 < 2, "You are really dumb into mathematics"); diff --git a/Sprint-2/1-key-errors/0.js b/Sprint-2/1-key-errors/0.js index 653d6f5a0..0172dcf8c 100644 --- a/Sprint-2/1-key-errors/0.js +++ b/Sprint-2/1-key-errors/0.js @@ -1,13 +1,16 @@ // Predict and explain first... -// =============> write your prediction here +// Guess init a variable with the same name than the argument is not a good idea. // call the function capitalise with a string input // interpret the error message and figure out why an error is occurring -function capitalise(str) { +/* function capitalise(str) { let str = `${str[0].toUpperCase()}${str.slice(1)}`; return str; -} +} */ -// =============> write your explanation here -// =============> write your new code here +// SyntaxError: Identifier 'str' has already been declared + function capitalise(str) { + return `${str[0].toUpperCase()}${str.slice(1)}`; +} +console.log(capitalise("hello world")); \ No newline at end of file diff --git a/Sprint-2/1-key-errors/1.js b/Sprint-2/1-key-errors/1.js index f2d56151f..21f5fad55 100644 --- a/Sprint-2/1-key-errors/1.js +++ b/Sprint-2/1-key-errors/1.js @@ -1,20 +1,27 @@ // Predict and explain first... // Why will an error occur when this program runs? -// =============> write your prediction here +// Variable 'decimalNumber' is already declared. And this declaration is no needed. +// console.log(decimalNumber); will throw an error. const is block scoped. // Try playing computer with the example to work out what is going on -function convertToPercentage(decimalNumber) { +/* function convertToPercentage(decimalNumber) { const decimalNumber = 0.5; const percentage = `${decimalNumber * 100}%`; return percentage; } -console.log(decimalNumber); +console.log(decimalNumber); */ -// =============> write your explanation here +// SyntaxError: Identifier 'decimalNumber' has already been declared // Finally, correct the code to fix the problem -// =============> write your new code here +function convertToPercentage(decimalNumber) { + const percentage = `${decimalNumber * 100}%`; + return percentage; +} + +console.log(convertToPercentage(0.5)); + diff --git a/Sprint-2/1-key-errors/2.js b/Sprint-2/1-key-errors/2.js index aad57f7cf..9c1401df6 100644 --- a/Sprint-2/1-key-errors/2.js +++ b/Sprint-2/1-key-errors/2.js @@ -3,18 +3,23 @@ // this function should square any number but instead we're going to get an error -// =============> write your prediction of the error here +// '3' is a number not an argument. -function square(3) { +/* function square(3) { return num * num; -} +} */ -// =============> write the error message here +// SyntaxError: Unexpected number -// =============> explain this error message here +// '3' is a number not an argument. +// An argument is a variable and must not begin with a number. +// the var 'num' is coming from nowhere. // 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..56763df67 100644 --- a/Sprint-2/2-mandatory-debug/0.js +++ b/Sprint-2/2-mandatory-debug/0.js @@ -1,14 +1,17 @@ // Predict and explain first... -// =============> write your prediction here +// The result of multiplying 10 and 32 is undefined -function multiply(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 +// No return in the function // 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..017f2ba34 100644 --- a/Sprint-2/2-mandatory-debug/1.js +++ b/Sprint-2/2-mandatory-debug/1.js @@ -1,13 +1,17 @@ // Predict and explain first... -// =============> write your prediction here +// The sum of 10 and 32 is undefined -function sum(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 +// return nothing. // 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..b9527877b 100644 --- a/Sprint-2/2-mandatory-debug/2.js +++ b/Sprint-2/2-mandatory-debug/2.js @@ -1,11 +1,28 @@ // Predict and explain first... // Predict the output of the following code: -// =============> Write your prediction here +// No argument passed in the function. +// the number value is always 103; -const num = 103; +/* + const num = 103; -function getLastDigit() { + function getLastDigit() { + return num.toString().slice(-1); + } + + console.log(`The last digit of 42 is ${getLastDigit(42)}`); + console.log(`The last digit of 105 is ${getLastDigit(105)}`); + console.log(`The last digit of 806 is ${getLastDigit(806)}`); +*/ + +// Now run the code and compare the output to your prediction +// The last digit of 806 is 3 +// Explain why the output is the way it is +// the num value is always 103 (const num = 103) +// Finally, correct the code to fix the problem + +function getLastDigit(num) { return num.toString().slice(-1); } @@ -13,12 +30,5 @@ console.log(`The last digit of 42 is ${getLastDigit(42)}`); console.log(`The last digit of 105 is ${getLastDigit(105)}`); console.log(`The last digit of 806 is ${getLastDigit(806)}`); -// Now run the code and compare the output to your prediction -// =============> write the output here -// Explain why the output is the way it is -// =============> write your explanation here -// Finally, correct the code to fix the problem -// =============> write your new code here - // This program should tell the user the last digit of each number. // Explain why getLastDigit is not working properly - correct the problem diff --git a/Sprint-2/3-mandatory-implement/1-bmi.js b/Sprint-2/3-mandatory-implement/1-bmi.js index 17b1cbde1..f4abae0e9 100644 --- a/Sprint-2/3-mandatory-implement/1-bmi.js +++ b/Sprint-2/3-mandatory-implement/1-bmi.js @@ -15,5 +15,8 @@ // It should return their Body Mass Index to 1 decimal place function calculateBMI(weight, height) { - // return the BMI of someone based off their weight and height -} \ No newline at end of file + // return the BMI of someone based off their weight and height. + return (weight / (height * height)).toFixed(1); +} + +console.log(`Bob's Body Mass Index is ${calculateBMI(120, 1.6)}`); diff --git a/Sprint-2/3-mandatory-implement/2-cases.js b/Sprint-2/3-mandatory-implement/2-cases.js index 5b0ef77ad..4de600bf2 100644 --- a/Sprint-2/3-mandatory-implement/2-cases.js +++ b/Sprint-2/3-mandatory-implement/2-cases.js @@ -14,3 +14,9 @@ // You will need to come up with an appropriate name for the function // Use the MDN string documentation to help you find a solution // This might help https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase + +function getUpperSnakeCase(str) { + return str.toUpperCase().trim().replace(/\s/g, "_"); +} +const str = " once upon a time "; +console.log(`'${str}' in UPPER_SNAKE_CASE is '${getUpperSnakeCase(str)}'.`); diff --git a/Sprint-2/3-mandatory-implement/3-to-pounds.js b/Sprint-2/3-mandatory-implement/3-to-pounds.js index 6265a1a70..1e7c6a243 100644 --- a/Sprint-2/3-mandatory-implement/3-to-pounds.js +++ b/Sprint-2/3-mandatory-implement/3-to-pounds.js @@ -4,3 +4,19 @@ // 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(pences){ + + const penceWithoutTrailingP = pences.substring( 0,pences.length - 1); + const paddedPenceNumberStr = penceWithoutTrailingP.padStart(3, "0"); + const pounds = paddedPenceNumberStr.substring( 0, paddedPenceNumberStr.length - 2 ); + const pence = paddedPenceNumberStr + .substring(paddedPenceNumberStr.length - 2) + .padEnd(2, "0"); + + return `£${pounds}.${pence}`; +} +const pences = ["399p", "1600p", "50p", "200p"]; + for (p of pences){ + console.log(`${p} is ${toPound(p)}`); + } \ No newline at end of file diff --git a/Sprint-2/4-mandatory-interpret/time-format.js b/Sprint-2/4-mandatory-interpret/time-format.js index 7c98eb0e8..492dfa0d5 100644 --- a/Sprint-2/4-mandatory-interpret/time-format.js +++ b/Sprint-2/4-mandatory-interpret/time-format.js @@ -1,5 +1,6 @@ function pad(num) { - return num.toString().padStart(2, "0"); + const result = num.toString().padStart(2, "0"); + return result; } function formatTimeDisplay(seconds) { @@ -7,28 +8,29 @@ function formatTimeDisplay(seconds) { const totalMinutes = (seconds - remainingSeconds) / 60; const remainingMinutes = totalMinutes % 60; const totalHours = (totalMinutes - remainingMinutes) / 60; + console.log("remainingSeconds",remainingSeconds); return `${pad(totalHours)}:${pad(remainingMinutes)}:${pad(remainingSeconds)}`; } - -// 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 +console.log("formatTimeDisplay(61)", formatTimeDisplay(61)); // Questions // a) When formatTimeDisplay is called how many times will pad be called? -// =============> write your answer here +// 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 +// 0 // c) What is the return value of pad is called for the first time? -// =============> write your answer here +// "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 +// d) What is the value assigned to num when pad is called for the last time in this program? +// Explain your answer +// Remaining seconds => 1 (61 seconds) -// e) What is the return value assigned to num when pad is called for the last time in this program? Explain your answer -// =============> write your answer here +// e) What is the return value assigned to num when pad is called for the last time in this program? +// Explain your answer +// "01" => pad fill the string < 2 with 0. diff --git a/Sprint-3/1-implement-and-rewrite-tests/implement/1-get-angle-type.js b/Sprint-3/1-implement-and-rewrite-tests/implement/1-get-angle-type.js index ca1dfe7f2..613416997 100644 --- a/Sprint-3/1-implement-and-rewrite-tests/implement/1-get-angle-type.js +++ b/Sprint-3/1-implement-and-rewrite-tests/implement/1-get-angle-type.js @@ -6,13 +6,23 @@ // The assertion error will tell you what the expected output is // Write the code to pass the test // Then, write the next test! :) Go through this process until all the cases are implemented - function getAngleType(angle) { - if (angle === 90) { + // Case 1: Identify Right Angles: + // When the angle is exactly 90 degrees, + if (angle < 90) { + return "Acute angle"; + } else if (angle === 90) { return "Right 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 { + const result = angle - 360; + return getAngleType(result); } - // Run the tests, work out what Case 2 is testing, and implement the required code here. - // Then keep going for the other cases, one at a time. } // The line below allows us to load the getAngleType function into tests in other files. @@ -50,14 +60,15 @@ 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(3597); +assertEquals(reflex, "Reflex angle"); \ No newline at end of file diff --git a/Sprint-3/1-implement-and-rewrite-tests/implement/2-is-proper-fraction.js b/Sprint-3/1-implement-and-rewrite-tests/implement/2-is-proper-fraction.js index a4739af77..4951fc4f0 100644 --- a/Sprint-3/1-implement-and-rewrite-tests/implement/2-is-proper-fraction.js +++ b/Sprint-3/1-implement-and-rewrite-tests/implement/2-is-proper-fraction.js @@ -11,6 +11,7 @@ function isProperFraction(numerator, denominator) { if (numerator < denominator) { return true; } + return false; } // The line below allows us to load the isProperFraction function into tests in other files. @@ -46,14 +47,14 @@ 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? diff --git a/Sprint-3/1-implement-and-rewrite-tests/implement/3-get-card-value.js b/Sprint-3/1-implement-and-rewrite-tests/implement/3-get-card-value.js index 266525d1b..e4790c8c6 100644 --- a/Sprint-3/1-implement-and-rewrite-tests/implement/3-get-card-value.js +++ b/Sprint-3/1-implement-and-rewrite-tests/implement/3-get-card-value.js @@ -6,11 +6,34 @@ // the first test and first case is written for you // 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) { +// just make one change at a time -- don't rush -- programmers are deep and careful thinkers. + +/* function getCardValue(card) { + const rank = card.charAt(0); if (rank === "A") { return 11; } +} */ +function getCardValue(card) { + if(typeof card !== 'string' || card.length > 2 || !["♠", "♣︎", "♦︎","♥"].includes(card.charAt(1)) ){ + throw new Error("Invalid card rank."); + } + // Set values to be tested. + const rank = card.charAt(0); + const nb = +rank; + // Numbers range 2-10. + if(!isNaN(nb) && (nb >= 2 && nb <=10 ) ){ + return nb; + } + // Ace. + else if (rank === "A") { + return 11; + // King Queen Valet. + } else if (["J", "Q", "K"].includes(rank)) { + return 10; + } + // Others. + throw new Error("Invalid card rank."); } // The line below allows us to load the getCardValue function into tests in other files. @@ -26,6 +49,7 @@ function assertEquals(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), @@ -39,19 +63,34 @@ assertEquals(aceofSpades, 11); // 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). 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 queenofHearts = getCardValue("Q♥"); +assertEquals(queenofHearts, 10); // 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. +const aceofHeart = getCardValue("A♥"); +assertEquals(aceofHeart, 11); // 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." +try{ + const error1 = getCardValue("1♥"); +//assertEquals(error1, false); +const error2 = getCardValue(67); +//assertEquals(error2, false); + +} +catch(e){ + assertEquals(e.message, "Invalid card rank."); +} + diff --git a/Sprint-3/1-implement-and-rewrite-tests/rewrite-tests-with-jest/1-get-angle-type.test.js b/Sprint-3/1-implement-and-rewrite-tests/rewrite-tests-with-jest/1-get-angle-type.test.js index 4a92a3e82..0338f4d9f 100644 --- a/Sprint-3/1-implement-and-rewrite-tests/rewrite-tests-with-jest/1-get-angle-type.test.js +++ b/Sprint-3/1-implement-and-rewrite-tests/rewrite-tests-with-jest/1-get-angle-type.test.js @@ -12,15 +12,27 @@ test("should identify right angle (90°)", () => { // 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 (angle < 90°)", () => { + expect(getAngleType(85)).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 ( 90° < angle > 180°)", () => { + expect(getAngleType(120)).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 (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, // Then the function should return "Reflex angle" +test("should identify reflex angle (180° < angle > 360°)", () => { + expect(getAngleType(350)).toEqual("Reflex angle"); +}); diff --git a/Sprint-3/1-implement-and-rewrite-tests/rewrite-tests-with-jest/2-is-proper-fraction.test.js b/Sprint-3/1-implement-and-rewrite-tests/rewrite-tests-with-jest/2-is-proper-fraction.test.js index caf08d15b..8963d85e3 100644 --- a/Sprint-3/1-implement-and-rewrite-tests/rewrite-tests-with-jest/2-is-proper-fraction.test.js +++ b/Sprint-3/1-implement-and-rewrite-tests/rewrite-tests-with-jest/2-is-proper-fraction.test.js @@ -7,7 +7,16 @@ test("should return true for a proper fraction", () => { }); // Case 2: Identify Improper Fractions: +test("should return true for an improper fraction", () => { + expect(isProperFraction(56, 3)).toEqual(false); +}); // Case 3: Identify Negative Fractions: +test("should return true for a negative Fraction", () => { + expect(isProperFraction(-26, 3)).toEqual(true); +}); // Case 4: Identify Equal Numerator and Denominator: +test("should return false for an equal Numerator and Denominator fraction", () => { + expect(isProperFraction(3, 3)).toEqual(false); +}); diff --git a/Sprint-3/1-implement-and-rewrite-tests/rewrite-tests-with-jest/3-get-card-value.test.js b/Sprint-3/1-implement-and-rewrite-tests/rewrite-tests-with-jest/3-get-card-value.test.js index 04418ff72..454396400 100644 --- a/Sprint-3/1-implement-and-rewrite-tests/rewrite-tests-with-jest/3-get-card-value.test.js +++ b/Sprint-3/1-implement-and-rewrite-tests/rewrite-tests-with-jest/3-get-card-value.test.js @@ -2,12 +2,37 @@ // We will use the same function, but write tests for it using Jest in this file. const getCardValue = require("../implement/3-get-card-value"); -test("should return 11 for Ace of Spades", () => { +test("Should return 11 for Ace of Spades", () => { const aceofSpades = getCardValue("A♠"); expect(aceofSpades).toEqual(11); }); // Case 2: Handle Number Cards (2-10): +test("Should return the number range (2-10).", () => { + expect(() => getCardValue("5♣︎").toEqual(5)); + expect(() => getCardValue("6♣︎").toEqual(6)); + expect(() => getCardValue("4♣︎").toEqual(4)); + expect(() => getCardValue("3♣︎").toEqual(3)); +}); // Case 3: Handle Face Cards (J, Q, K): +test("Should return 1° for Face Cards (J, Q, K).", () => { + expect(() => getCardValue("J♣︎").toEqual(10)); + expect(() => getCardValue("Q♠").toEqual(10)); + expect(() => getCardValue("K♣︎").toEqual(10)); + expect(() => getCardValue("K♥").toEqual(10)); +}); // Case 4: Handle Ace (A): +test("Should return 1° for Ace (A).", () => { + expect(() => getCardValue("A♣︎").toEqual(11)); + expect(() => getCardValue("A♠").toEqual(11)); + expect(() => getCardValue("A♦︎").toEqual(11)); + expect(() => getCardValue("A♥").toEqual(11)); +}); // Case 5: Handle Invalid Cards: +test("Should throw an error for invalid cards", () => { + expect(() => getCardValue("1♠")).toThrowError("Invalid card rank."); + expect(() => getCardValue("X♥")).toThrowError("Invalid card rank."); + expect(() => getCardValue("A")).toThrowError("Invalid card rank."); + expect(() => getCardValue("A♠♠")).toThrowError("Invalid card rank."); + expect(() => getCardValue(123)).toThrowError("Invalid card rank."); +}); diff --git a/Sprint-3/2-practice-tdd/count.js b/Sprint-3/2-practice-tdd/count.js index 95b6ebb7d..b89d32cfd 100644 --- a/Sprint-3/2-practice-tdd/count.js +++ b/Sprint-3/2-practice-tdd/count.js @@ -1,5 +1,8 @@ function countChar(stringOfCharacters, findCharacter) { - return 5 + const regExp = new RegExp(findCharacter, "g"); + const match = stringOfCharacters.match(regExp); + return match ? match.length : 0; } module.exports = countChar; + diff --git a/Sprint-3/2-practice-tdd/count.test.js b/Sprint-3/2-practice-tdd/count.test.js index 42baf4b4b..0e3387c4e 100644 --- a/Sprint-3/2-practice-tdd/count.test.js +++ b/Sprint-3/2-practice-tdd/count.test.js @@ -11,10 +11,14 @@ const countChar = require("./count"); // 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"; - const count = countChar(str, char); - expect(count).toEqual(5); + + const count1 = countChar("aaaaa", "a"); + const count2 = countChar("Once Upon A Time A litle Rabbit Called Anastasia","a"); + const count3 = countChar("ON Litle Italy on my heart on very hours","on"); + + expect(count1).toEqual(5); + expect(count2).toEqual(5); + expect(count3).toEqual(2); }); // Scenario: No Occurrences diff --git a/Sprint-3/2-practice-tdd/get-ordinal-number.js b/Sprint-3/2-practice-tdd/get-ordinal-number.js index f95d71db1..1086a95f3 100644 --- a/Sprint-3/2-practice-tdd/get-ordinal-number.js +++ b/Sprint-3/2-practice-tdd/get-ordinal-number.js @@ -1,5 +1,14 @@ function getOrdinalNumber(num) { - return "1st"; + const suffix = ["th", "st", "nd", "rd"]; + /* + * For numbers greater than or equal to 100, n % 100 extracts the last two digits, + * allowing cases like 111, 112, and 113 to be handled in the same way as 11, 12, and 13. + */ + const n = num % 100; + /* + * (n - 20) % 10 => negatif || 0 + */ + return num + (suffix[(n - 20) % 10] || suffix[n] || suffix[0]); } module.exports = getOrdinalNumber; diff --git a/Sprint-3/2-practice-tdd/get-ordinal-number.test.js b/Sprint-3/2-practice-tdd/get-ordinal-number.test.js index dfe4b6091..3e4aab7de 100644 --- a/Sprint-3/2-practice-tdd/get-ordinal-number.test.js +++ b/Sprint-3/2-practice-tdd/get-ordinal-number.test.js @@ -11,3 +11,12 @@ 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 '113th' for 113", () => { + expect(getOrdinalNumber(113)).toEqual("113th"); +}); diff --git a/Sprint-3/2-practice-tdd/repeat.js b/Sprint-3/2-practice-tdd/repeat.js index 00e60d7f3..b0e7447a3 100644 --- a/Sprint-3/2-practice-tdd/repeat.js +++ b/Sprint-3/2-practice-tdd/repeat.js @@ -1,5 +1,16 @@ -function repeat() { - return "hellohellohello"; +function repeat(str, repeat) { + if (repeat < 0) { + throw new Error("Negative counts are not valid."); + } + if (repeat === 1) { + return str; + } + + let output = ""; + for (let i = 0; i < repeat; i++) { + output += str; + } + return output; } module.exports = repeat; diff --git a/Sprint-3/2-practice-tdd/repeat.test.js b/Sprint-3/2-practice-tdd/repeat.test.js index 34097b09c..462799324 100644 --- a/Sprint-3/2-practice-tdd/repeat.test.js +++ b/Sprint-3/2-practice-tdd/repeat.test.js @@ -10,23 +10,31 @@ const repeat = require("./repeat"); // Then it should repeat the str count times and return a new string containing the repeated str values. test("should repeat the string count times", () => { - const str = "hello"; - const count = 3; - const repeatedStr = repeat(str, count); - expect(repeatedStr).toEqual("hellohellohello"); + expect(repeat("Hello", 3)).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. +test("should return the original string", () => { + expect(repeat("Hello", 1)).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. +test("should return an empty string", () => { + expect(repeat("Hello", 0)).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 if count is negative", () => { + + expect(() => repeat("Hello", -15)).toThrowError("Negative counts are not valid."); + +}); diff --git a/Sprint-3/3-stretch/card-validator.js b/Sprint-3/3-stretch/card-validator.js new file mode 100644 index 000000000..74a33a888 --- /dev/null +++ b/Sprint-3/3-stretch/card-validator.js @@ -0,0 +1,95 @@ +/* +Here are the rules for a valid number: + +- Number must be 16 digits, all of them must be numbers. +- You must have at least two different digits represented (all of the digits cannot be the same). +- The final digit must be even. +- The sum of all the digits must be greater than 16. + +For example, the following credit card numbers are valid: + +9999777788880000 +6666666666661666 + +And the following credit card numbers are invalid: + +```markdown +a92332119c011112 (invalid characters) +4444444444444444 (only one type of number) +1111111111111110 (sum less than 16) +6666666666666661 (odd final number) +``` + +These are the requirements your project needs to fulfill: + +- Make a JavaScript file with a name that describes its contents. +- Create a function with a descriptive name which makes it clear what the function does. +- The function should take one argument, the credit card number to validate. +- Write at least 2 comments that explain to others what a line of code is meant to do. +- Return a boolean from the function to indicate whether the credit card number is valid. +*/ + +function cardValidator(num) { + // Store 16 + const numSize = 16; + // Cast to String: + const numStr = num.toString(); + // Cast to Array: + const numArr = [...numStr]; + // Final throw new Error message. + let errorMess = ""; + // Number must be 16 digits, all of them must be numbers. + if (isNaN(num) || numStr.length !== numSize) { + errorMess += `• Must be ${numSize} digits exactly.\n`; + } + // All of the digits cannot be the same. + /* const isSameNum = numArr.every((num) => num === numStr.charAt(0)); + if (isSameNum) { + errorMess += "• All same digits is not allowed.\n"; + } */ + // IA improvment proposal. + if (new Set(numStr).size === 1) { + errorMess += "• All same digits is not allowed.\n"; + } + + // The final digit must be even. + if (numArr[numArr.length - 1] % 2 === 1) { + errorMess += "• Last digit must be even.\n"; + } + // The sum of all the digits must be greater than 16. + let sum = numArr.reduce((acc, current) => acc + Number(current), 0); + if (sum <= numSize) { + errorMess += `• The digit's sum must be greater than ${numSize}.`; + } + + // Invalid card numbers : Throw Error. + if (errorMess) { + throw new Error("Invalid card numbers:\n" + errorMess); + } + // Valid card. + return true; +} + +module.exports = cardValidator; +// Output. +const cardNumbers = [ + 3003000330000000, + "a92332119c011112", + 4444444444444444, + 1111111111111110, + 6666666666666661, + 1117, + 1234666766806664, +]; +// Loop on cardNumbers array. +for (digits of cardNumbers) { + console.log("\ndigits", digits); + // Use try catch to handle the thrown errors. + try { + if (cardValidator(digits)) { + console.log(" 🎉 Your card is valid! 🎉 "); + } + } catch (e) { + console.error(e.message); + } +} diff --git a/Sprint-3/3-stretch/card-validator.md b/Sprint-3/3-stretch/card-validator.md deleted file mode 100644 index e39c6ace6..000000000 --- a/Sprint-3/3-stretch/card-validator.md +++ /dev/null @@ -1,35 +0,0 @@ -## **PROJECT: Credit Card Validator** - -In this project you'll write a script that validates whether or not a credit card number is valid. - -Here are the rules for a valid number: - -- Number must be 16 digits, all of them must be numbers. -- You must have at least two different digits represented (all of the digits cannot be the same). -- The final digit must be even. -- The sum of all the digits must be greater than 16. - -For example, the following credit card numbers are valid: - -```markdown -9999777788880000 -6666666666661666 -``` - -And the following credit card numbers are invalid: - -```markdown -a92332119c011112 (invalid characters) -4444444444444444 (only one type of number) -1111111111111110 (sum less than 16) -6666666666666661 (odd final number) -``` - -These are the requirements your project needs to fulfill: - -- Make a JavaScript file with a name that describes its contents. -- Create a function with a descriptive name which makes it clear what the function does. The function should take one argument, the credit card number to validate. -- Write at least 2 comments that explain to others what a line of code is meant to do. -- Return a boolean from the function to indicate whether the credit card number is valid. - -Good luck! diff --git a/Sprint-3/3-stretch/card-validator.test.js b/Sprint-3/3-stretch/card-validator.test.js new file mode 100644 index 000000000..361f3c17d --- /dev/null +++ b/Sprint-3/3-stretch/card-validator.test.js @@ -0,0 +1,16 @@ +const cardValidator = require("./card-validator"); + +test("Valid cart", () => { + const result = cardValidator(1234896766806664); + // Assert + expect(result).toEqual(true); +} +); +test("Invalid cart : Last Digit is odd", () => { + expect(() => cardValidator(6666666666666661).toThrowError()); +} +); +test("Invalid cart : All errors", () => { + expect(() => cardValidator(1111).toThrowError()); +} +); \ No newline at end of file diff --git a/Sprint-3/3-stretch/password-validator.js b/Sprint-3/3-stretch/password-validator.js index b55d527db..0c264b620 100644 --- a/Sprint-3/3-stretch/password-validator.js +++ b/Sprint-3/3-stretch/password-validator.js @@ -1,6 +1,36 @@ +/* +Password Validation + +Write a program that should check if a password is valid +and returns a boolean + +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. + +You must breakdown this problem in order to solve it. Find one test case first and get that working + +/* +Passwords examples. +Bonjour1! // +Az3&plus. +P4ssw.rd* +p4SSw.66* // +// +hello1! +hello! +*/ function passwordValidator(password) { - return password.length < 5 ? false : true + const previousPwd = ["Bonjour1!", "p4SSw.66*"]; + if (previousPwd.includes(password)) { + throw new Error("Password already used."); + } + const regExp = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!#$%.*&]).{5,}$/; + return regExp.test(password); } - -module.exports = passwordValidator; \ No newline at end of file +module.exports = passwordValidator; diff --git a/Sprint-3/3-stretch/password-validator.test.js b/Sprint-3/3-stretch/password-validator.test.js index 8fa3089d6..ce15dc2ea 100644 --- a/Sprint-3/3-stretch/password-validator.test.js +++ b/Sprint-3/3-stretch/password-validator.test.js @@ -15,12 +15,19 @@ 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 */ 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("Password is valid.", () => { + const result = isValidPassword("Az3&plus."); + expect(result).toEqual(true); +}); + +test("Password is invalid.", () => { + const result = isValidPassword("hello!"); + expect(result).toEqual(false); +}); + +test("Password has been already used.", () => { + expect(() => + isValidPassword("p4SSw.66*").toThrowError("Password already used.") + ); +});