Skip to content
This repository was archived by the owner on Apr 18, 2025. It is now read-only.

NW-6 | Zeliha Pala | JS1| [TECH ED] Complete week 4 exercises | WEEK-4 #188

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
3,603 changes: 3,603 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "week-4",
"description": "end of JS1",
"scripts": {
"test": "jest"
},
"devDependencies": {
"jest": "^29.7.0"
}
}
75 changes: 75 additions & 0 deletions week-4/implement/count.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,84 @@
// 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 consecutive occurrences of char (e.g., 'a' appears five times in 'aaaaa').
/*
function countChar(str, char) {
return str.split(char).length - 1;
}

const stringInput = "Harry Potter and the Philosopher's Stone";
const countCharacter = "o";
const result = countChar(stringInput, countCharacter);

console.log(
`The character '${countCharacter}' appears ${result} times consecutively in '${stringInput}'.`
);*/

// 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.

/*function countChar(str, char) {
let count = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === char) {
count++;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A good solution for the count. Also its better to keep clean code removing comment out lines. 👍

// checks if the current character in the string (str[i]) is equal to the character we’re searching for (char), and if true it increments the count variable by 1. This keeps happening for every letter in string. if not shows zero
}
return count;
}

const StringInput = "Harry Potter and the Philosopher's Stone";
const countCharacter = "e";

console.log(
`The character '${countCharacter}' appears ${countChar(
StringInput,
countCharacter
)} times in "${StringInput}".`
);
// Output: The character 'e' appears 4 times in "Harry Potter and the Philosopher's Stone".

const noOccurrenceChar = "z";

console.log(
`The character '${noOccurrenceChar}' appears ${countChar(
StringInput,
noOccurrenceChar
)} times in "${StringInput}".`
);
// Output The character 'z' appears 0 times in "Harry Potter and the Philosopher's Stone". */

function countChar(str, char) {
let count = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === char) {
count++;
}
}
return count;
}
const stringInput = "Harry Potter and the Philosopher's Stone";

function countChar(str, char) {
let count = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === char) {
count++;
}
}
return count;
}
//const stringInput = "Harry Potter and the Philosopher's Stone"; stringInput gives a redeclaration error in here. I cleared it and still working
test("countChar - character 'e'", () => {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test description part needs to be more specific explanation such as "works for multiple char occurrences" or "works for no char occurrences"

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@RbAvci Thank you for your review. You are right. I'll provide the explanations as you suggested.

const countCharacter = "e";
expect(countChar(stringInput, countCharacter)).toBe(4);
});

test("countChar - character 'z'", () => {
const noOccurrenceChar = "z";
expect(countChar(stringInput, noOccurrenceChar)).toBe(0);
});
18 changes: 18 additions & 0 deletions week-4/implement/get-ordinal-number.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,21 @@

// continue testing and implementing getOrdinalNumber for additional cases
// Write your tests using Jest - remember to run your tests often for continual feedback

function getOrdinalNumber() {
return "1st";
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The getOrdinalNumber function always returns "1st" regardless of the input. If you want the function to generate ordinal numbers based on the input dynamically, you must modify the function.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @RbAvci that was so helpful I worked on this exercise and fixed. Now test cases are working


test("converts 1 to an ordinal number", function () {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, you can write tests for numbers "2nd" and "3rd". In that way, you can fill in the logic inside the getOrdinalNumber function.

const input = 1;
const currentOutput = getOrdinalNumber(input);
const targetOutput = "1st";

expect(currentOutput).toBe(targetOutput);
});

test("works for any number ending in 1", function () {
expect(getOrdinalNumber(1)).toBe("1st");
expect(getOrdinalNumber(11)).toBe("11th");
expect(getOrdinalNumber(21)).toBe("21st");
});
36 changes: 36 additions & 0 deletions week-4/implement/is-prime.test.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,39 @@
// Given a positive integer num,
// When the isPrime function is called with num as input,
// Then it should return a boolean representing whether the num is prime

function isPrime(num) {
if (num <= 1 || Number.isInteger(num) === false) {
//if the number is smaller than or equal to 1 or if the number isn't a whole number return false
return false;
}

for (let i = 2; i <= num / 2; i++) {
// starts from 2 and, ( increase by 1) runs as long as the value of i is less than or equal to half of num

if (num % i === 0) {
//if num' is divisible by the value of i.
return false;
}
}

return true;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍


test("checks if number is prime number", function () {
// Numbers tested with different orderings

expect(isPrime(5)).toBe(true);
expect(isPrime(1)).toBe(false);
expect(isPrime(9)).toBe(false);
expect(isPrime(2)).toBe(true);
expect(isPrime(11)).toBe(true);
expect(isPrime(6)).toBe(false);
expect(isPrime(3)).toBe(true);
expect(isPrime(-3)).toBe(false);
expect(isPrime(4)).toBe(false);
expect(isPrime(7)).toBe(true);
expect(isPrime(2.5)).toBe(false);
expect(isPrime(0)).toBe(false);
expect(isPrime(15.75)).toBe(false);
});
24 changes: 24 additions & 0 deletions week-4/implement/password-validator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,27 @@ To be valid, a password must:

You must breakdown this problem in order to solve it. Find one test case first and get that working
*/

function validatePassword(password, previousPasswords) {
return (
password.length >= 5 &&
/[A-Z]/.test(password) &&
/[a-z]/.test(password) &&
/\d/.test(password) && // checks if the password contains at least one digit (0-9).
/[!#$%.&*]/.test(password) && //if the password contains at least one of the specified symbols
!previousPasswords.includes(password) // if the password is not present in the previousPasswords
);
}

test("Validating passwords against prior usage", () => {
const previousPasswords = ["greenworld39", "mimoza@!09", "whoisThere?"];

// valid password
expect(validatePassword("greenworld@39", previousPasswords)).toBe(true);

// previousPasswords
expect(validatePassword("mimoza@!09", previousPasswords)).toBe(false);

// invalid password (doesn't meet criteria)
expect(validatePassword("weak", previousPasswords)).toBe(false);
});
22 changes: 22 additions & 0 deletions week-4/implement/repeat.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,25 @@
// 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.

function repeat(str, count) {
if (count < 0) {
throw new Error("Negative counts are not valid.");
} else if (count === 0) {
return "";
} else if (count === 1) {
return str;
} else {
return str.repeat(count);
}
Comment on lines +30 to +36
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need to check 0 and 1 values? What would happen if we called str.repeat(0) or str.repeat(1)?

}
// The function 'repeat' takes a string and a count as inputs. It checks if the count is negative; if it is, an error is returned. If the count is zero, an empty string is returned. When the count is one, the original string is returned. If the count is greater than one, the function repeats the string 'count' times and returns the resulting concatenated string.

test("Managing text repetition with error control.", function () {
expect(repeat("Cyf", 3)).toBe("CyfCyfCyf");
expect(repeat("Manchester", 1)).toBe("Manchester");
expect(repeat("istanbul", 0)).toBe("");
expect(repeat("London", 2)).toBe("LondonLondon");
expect(() => repeat("Moracco", -1)).toThrow("Negative counts are not valid.");
});
// toThrow is used here to verify that the function actually throws an error when given a negative count, and it checks if the error message matches the expected one.
42 changes: 42 additions & 0 deletions week-4/implement/valid-credit-card-number.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
function validCardNumber(cardNumber) {
//if the input is not a number or is not 16 digits
if (isNaN(cardNumber) || cardNumber.length !== 16) {
return false;
}

// here .split is taking string of numbers and splitting it into individual parts like "2" "6" and .map takes each of those individual parts and converts them into numbers.
const eachNum = cardNumber.split("").map(Number);

// if all numbers are the same
const isSame = eachNum.every((eachNums) => eachNums === eachNum[0]);
if (isSame) {
return false;
}

// if the final number is even
if (eachNum[15] % 2 !== 0) {
return false;
}

// Calculate the sum of all numbers
const sum = eachNum.reduce((total, eachNums) => total + eachNums, 0);

// if the sum is greater than 16
if (sum <= 16) {
return false;
}

return true;
}

// Test cases

console.log(validCardNumber("3333333333333330")); // true
console.log(validCardNumber("2222222222222222")); // false

console.log(validCardNumber("3549777788880000")); // true
console.log(validCardNumber("6236699363666166")); // true

console.log(validCardNumber("a92332119c011112")); // false

console.log(validCardNumber("4999999999999999")); // false
23 changes: 17 additions & 6 deletions week-4/investigate/find.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
function find(str, char) {
let index = 0;
// to clarify this part here is an example: Suppose the function is given the string "hello" and the character 'o'. In this case, the function will determine at which index the character 'o' is located within this string.

while (index < str.length) {
if (str[index] === char) {
Expand All @@ -10,16 +11,26 @@ function find(str, char) {
return -1;
}

console.log(find("code your future", "u"));
console.log(find("code your future", "z"));
// it starts checking the characters one by one and begins with the character at the 0th index, which is 'h'. If this character isn't 'o', the index value is increased by 1 to check the next character.
//it continues checking each character in sequence. When it finds the 'o' character, the function returns its position (for instance, 3) and stops the search. If the 'o' character isn't found, the function returns -1.

console.log(find("code your future", "u")); //7
console.log(find("code your future", "z")); // -1

// The while loop statement allows us to do iteration - the repetition of a certain number of tasks according to some condition
// See the docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while

// Use the Python Visualiser to help you play computer with this example and observe how this code is executed
// 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
// c) Why is index++ being used?
// d) What is the condition index < str.length used for?
/*a) How the index variable updates during the call to find
The index variable updates in find by incrementing using index++ within the while loop, moving through str's characters one by one. */

/* b) What is the if statement used to check
The if statement if (str[index] === char) is used to check if the character at the current index in the string (str[index]) matches the specified character char.*/

/* c) Why is index++ being used?
index++ increments the variable after each loop, to advance to the next character in the string.*/

/* d) What is the condition index < str.length used for?
The condition index < str.length prevents the loop from searching beyond the string's length while finding the character. */