Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion 01/assets/js/app.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,50 @@
const a = '4.2';
const b = 9;

console.log(a, b);
console.log(a, b);

// 1. Check the types of variables
console.log("Type of variable a: ", typeof a); // string
console.log("Type of variable b: ", typeof b); // number

// 2. Arithmetic operations
// Convert 'a' to a number to avoid string concatenation
const addition = parseFloat(a) + b;

const subtraction = a - b;
const multiplication = a * b;
const division = a / b;
const modulo = a % b;
const exponentiation = a ** b;

// console.log("Addition: ", addition);
// console.log("Subtraction: ", subtraction);
// console.log("Multiplication: ", multiplication);
// console.log("Division: ", division);
// console.log("Modulo: ", modulo);
// console.log("Exponentiation: ", exponentiation);

// 3. Check which result is greater than 20, which is less than 20 and which is equal to 20
const results = [
Copy link
Owner

Choose a reason for hiding this comment

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

Zastanawiam się czy nie lepiej byłoby zrobić z tego funkcję, która przyjmuje przez parametr nazwy oraz funkcji z działaniem. Natomiast 2 parametry to coś stałego, co potem można przekazać. Może dałoby się do tego wykorzystać wzorzec obserwator: https://refactoring.guru/pl/design-patterns/observer

{ name: 'Addition', value: addition },
{ name: 'Subtraction', value: subtraction },
{ name: 'Multiplication', value: multiplication },
{ name: 'Division', value: division },
{ name: 'Modulo', value: modulo },
{ name: 'Exponentiation', value: exponentiation }
];

results.forEach(result => {
if (!result || typeof result.value !== 'number' || typeof result.name !== 'string') {
console.error('Invalid result object encountered:', result);
return;
}

if (result.value > 20) {
console.log(`${result.name} result ${result.value} is greater than 20.`);
} else if (result.value < 20) {
console.log(`${result.name} result ${result.value} is less than 20.`);
} else {
console.log(`${result.name} result ${result.value} is equal to 20.`);
}
});
2 changes: 1 addition & 1 deletion 01/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@
<title>devmentor.pl - JS BASICS - #01</title>
</head>
<body>

<script src="assets/js/app.js"></script>
</body>
</html>
46 changes: 44 additions & 2 deletions 02/app.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,49 @@

/* rozwiązanie z pętlą for */
const x = 4;

const input = prompt('Enter the multiplication factor: ');
const x = Number(input);

if (isNaN(x)) {
Copy link
Owner

Choose a reason for hiding this comment

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

Lepiej zdefiniować funkcję, która sprawdza poprawność danych - wtedy tych if-ów jest mniej i kod jest czytelniejszy.

PS. Może w samej funkcji tych if-ów jest mniej, ale do jej zawartości nie zaglądamy czytając kod - wystarczy jej nazwa, aby sie zorientować o co chodzi.

if(isCorrect()) {
  // operacja
} else {
  // komunikat
}

console.error(`Provided value (${input}) is not a number`);
} else if (!Number.isInteger(x)) {
console.error(`Provided value (${x}) is not an integer`);
} else if (x < 1 || x > 9) {
console.error(`Provided value (${x}) is not between 1 and 9`);
} else {
for (let i = 1; i <= 9; i++) {
console.log(`${x} * ${i} = ${x * i}`);
}
}

/* rozwiązanie z pętlą while */
/* rozwiązanie z pętlą while */
Copy link
Owner

Choose a reason for hiding this comment

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

Wiem, że w zadaniu nie było napisane, ale zdecydowanie ten kod można podzielić na funkcje.


const baseInput = prompt('Enter the base number for exponentiation (a): ');
const a = Number(baseInput);

const exponentInput = prompt('Enter the exponent (n): ');
const n = Number(exponentInput);

if (isNaN(a) || !Number.isInteger(a)) {
console.error(`Base must be an integer. Provided value: ${baseInput}`);
} else if (isNaN(n) || !Number.isInteger(n) || n < 1) {
console.error(`Exponent must be an integer greater than or equal to 1. Provided value: ${exponentInput}`);
} else {
let i = 0;
let result = 1;
let chain = "";

while (i < n) {
result *= a;

if (i === 0) {
chain += a;
} else {
chain += " * " + a;
}

i++;
}

console.log(`${chain} = ${result}`);
}
2 changes: 1 addition & 1 deletion 02/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@
<title>devmentor.pl - JS BASICS - #02</title>
</head>
<body>

<script src="./app.js"></script>
</body>
</html>
45 changes: 39 additions & 6 deletions 03/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,45 @@ const c = randomNumber(min, max);

console.log(a, b, c);






function getSum(a, b, c) {
a = parseInt(a, 10);
b = parseInt(b, 10);
c = parseInt(c, 10);

return a + b + c - Math.min(a, b, c);
Copy link
Owner

Choose a reason for hiding this comment

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

ooo super rozwiązanie! Sam był użył sort() i wybrał 2 największe ;P

}

const isEven = function (a) {
if (typeof a !== 'number') return null;

return a % 2 === 0;
};

function showInfo(a, b) {
let message;

switch (b) {
case null:
message = `The provided argument ${a} is not a number.`;
break;
case true:
message = `The provided argument ${a} is even.`;
break;
case false:
message = `The provided argument ${a} is odd.`;
break;
default:
message = `Invalid value for the second parameter: ${b}`;
}

console.log(message);
}

function randomNumber(min, max) {
return Math.round((Math.random() * (max - min)) + min);
}
}

const sum = getSum(a, b, c);
const even = isEven(sum);

showInfo(sum, even);
33 changes: 33 additions & 0 deletions 04/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const createArray = (min, max) => {
const arr = [];

for (let i = 0; i < 20; i++) {
arr.push(getRandomInt(min, max));
}
return arr;
};

const getRandomInt = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min; //Assumption: both min & max parameters are integers
};

const getLargest = arr => {
if (!Array.isArray(arr) || arr.length === 0) return null;

return [...arr].sort((a, b) => b - a).slice(0, 10);
Copy link
Owner

Choose a reason for hiding this comment

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

super, że utworzyłeś kopie!

};


const getAverage = arr => {
if (!Array.isArray(arr) || arr.length === 0) return null;

return arr.reduce((sum, num) => sum + num, 0) / arr.length;
};

const testArr = createArray(10, 200);
const largestNumbersArray = getLargest(testArr);
const averageFromLargest = getAverage(largestNumbersArray);

console.log(testArr);
console.log(largestNumbersArray);
console.log(averageFromLargest);
2 changes: 1 addition & 1 deletion 04/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@
<title>devmentor.pl - JS BASICS - #04</title>
</head>
<body>

<script src="./app.js"></script>
</body>
</html>
61 changes: 61 additions & 0 deletions 05/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
class Student {
Copy link
Owner

Choose a reason for hiding this comment

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

Rozumiem, że konstruktory to zaszłość, ale w zadaniu byłą mowa o nich to lepiej się trzymać treści zadania (nie chodzi o mnie, ale o potencjalną rekrutację)

constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.grades = {};
}

// Static method to normalize subject names
static normalizeSubject(subject) {
return subject.trim().toLowerCase() //this could be adjusted further if we decide to handle spaces in subject names differently, perhaps by adding: .replace(/\s+/g, '_')
}
Copy link
Owner

Choose a reason for hiding this comment

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

👍


// Static method to compute the average of an array of numbers.
static computeAverage(arr) {
if (!Array.isArray(arr) || arr.length === 0) return null;

const sum = arr.reduce((acc, num) => acc + num, 0);

return sum / arr.length;
}
Copy link
Owner

Choose a reason for hiding this comment

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

👍


addGrade(subject, grade) {
if (typeof subject !== 'string' || subject.trim() === '') {
throw new Error('Subject must be a non-empty string');
}
if (typeof grade !== 'number' || isNaN(grade)) {
throw new Error('Grade must be a valid number');
}

const subjectKey = Student.normalizeSubject(subject);
Copy link
Owner

Choose a reason for hiding this comment

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

Może zamiast pamiętać za każdym razem, aby "normalizować" subject, to napisać metodę getGradesBySubject() i tam wykonywać odpowiedniego sprawdzenia + normalizacji itp. - łatwiej będzie utrzymać porządek.


if (!this.grades[subjectKey]) {
this.grades[subjectKey] = [];
}

this.grades[subjectKey].push(grade);
}

getAverageGrade(subject) {
const gradesToCalculate = (typeof subject === 'string' && subject.trim())
? (this.grades[Student.normalizeSubject(subject)] || [])
: Object.values(this.grades).flat();

return Student.computeAverage(gradesToCalculate);
}
}

const student = new Student('Jan', 'Kowalski');
student.addGrade('maths', 4);
student.addGrade('maths', 6);
student.addGrade('english', 3);
student.addGrade('english', 6);

const avgMath = student.getAverageGrade('maths');
const avgEnglish = student.getAverageGrade('english');
const overallAvg = student.getAverageGrade();

console.log(student);
console.log('Average Maths:', avgMath);
console.log('Average English:', avgEnglish);
console.log('Overall Average:', overallAvg);
2 changes: 1 addition & 1 deletion 05/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@
<title>devmentor.pl - JS BASICS - #05</title>
</head>
<body>

<script src="./app.js"></script>
</body>
</html>