init new course

This commit is contained in:
Philippe Torrel
2026-09-06 23:00:53 +02:00
parent 4875204025
commit c5115d81f6
9921 changed files with 4 additions and 1160514 deletions
@@ -1,80 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 14: Durchschnittsnoten berechnen</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 14: Durchschnittsnoten berechnen</h2>
<p>
Durchschnitt pro Schüler (<strong>calculateAvgGrades</strong>): Schreibe eine Funktion, die die
Durchschnittsnote jedes Schülers (zeilenweise) berechnet. Das Ergebnis soll ein Array mit den
Durchschnittswerten der Schüler (Anna, Ben, Clara, David) sein.
</p>
<p>
Durchschnitt pro Fach (<strong>calculateAvgSubjects</strong>): Schreibe eine Funktion, die die
Durchschnittsnote jedes Fachs (spaltenweise) berechnet. Das Ergebnis soll ein Array mit den
Durchschnittswerten der Fächer (Mathematics, English, Biology, History) sein.
</p>
<div class="output alert alert-secondary my-3"></div>
</div>
</div>
</main>
<script>
'use strict';
const outputEl = document.querySelector('.output');
const gradesTable = [
['Name', 'Mathematics', 'English', 'Biology', 'History'],
['Anna', 85, 92, 78, 88],
['Ben', 90, 88, 84, 79],
['Clara', 76, 95, 89, 91],
['David', 82, 79, 91, 85],
];
const calculateAverageGrades = (ar = []) => {
return ar.slice(1).map((row) => {
const grades = row.slice(1); // => [85, 92, 78, 88]
const avgGrades = grades.reduce((a, b) => a + b, 0) / grades.length;
return Number(avgGrades.toFixed(2));
});
};
// [].reduce((INDEX_A, INDEX_B) => {}, INITIAL_VALUE)
console.log(
[85, 92, 78, 88].reduce((sum, n) => {
return Number(sum) + Number(n);
}, 0),
); // => 343
const calculateAvgSubjects = (ar = []) => {
const entries = ar.slice(1);
const grades = entries.map((ar) => ar.slice(1));
console.log(grades);
// [
// []
// [85, 92, 78, 88]
// [90, 88, 84, 79]
// [76, 95, 89, 91]
// [82, 79, 91, 85]
// ]
const results = grades.reduce((resAr, nAr) => {
resAr.push(nAr[0]);
return resAr;
}, []);
console.log(results);
};
console.log(calculateAvgSubjects(gradesTable));
console.log(calculateAverageGrades(gradesTable));
outputEl.textContent = `Average grades of students are: ${calculateAverageGrades().join(' - ')}`;
</script>
</body>
</html>
@@ -1,38 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 1: Vorname vor Nachname oder Nachname vor Vorname?</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 1: Vorname vor Nachname oder Nachname vor Vorname?</h2>
<p>
Wenn dich der Name der Übung beim Lesen genauso verwirrt wie uns beim Schreiben, dann liegt das daran, dass
die Reihenfolge von Vor- und Nachnamen nicht immer eindeutig ist. Manchmal heißt es
<strong>Max Mustermann</strong> und manchmal auch <strong>Mustermann, Max</strong>. Damit Benutzer der
Funktion logTransformedName (aus der Übung Der transformierte Ladislaus, Teil 2 der letzten Class) nicht
auch so verwirrt sind, stelle sie besser auf <code>named parameters</code> um.
</p>
</div>
</div>
</main>
<script>
'use strict';
let logTransformedName = ({ firstName, lastName }) => {
console.log(`${lastName}, ${firstName.charAt(0)}.`);
};
const trainer = { lastName: 'Torrel', firstName: 'Philippe' };
logTransformedName({ firstName: 'Ladislaus', lastName: 'Jones' });
logTransformedName(trainer);
logTransformedName({ lastName: 'Rohleder', firstName: 'Andreas', isSmoker: true });
</script>
</body>
</html>
@@ -1,41 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 2: Ist es noch weit? Sind wir schon da?</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 2: Ist es noch weit? Sind wir schon da?</h2>
<p>Die Formel zur Berechnung von Entfernungen lautet:</p>
<code>
<pre>Math.sqrt((yDestination - yOrigin) ** 2 + (xDestination - xOrigin) ** 2);</pre>
</code>
<p>Schreibe eine Funktion distance, die du z. B. folgendermaßen aufrufen kannst:</p>
<code>
<pre>distance({ x: 1, y: 1 }, { x: 5, y: 1 }); // => 4</pre>
</code>
</div>
</div>
</main>
<script>
'use strict';
const distance = ({ x: xOrigin, y: yOrigin }, { x: xDest, y: yDest }) => {
return Math.sqrt((yDest - yOrigin) ** 2 + (xDest - xOrigin) ** 2);
};
// RECOMMENDED without destructuring
const getDistance = (origin, dest) => {
return Math.sqrt((dest.y - origin.y) ** 2 + (dest.x - origin.x) ** 2);
};
console.log('Die Distanz beträgt: ', distance({ x: 1, y: 1 }, { x: 5, y: 1 }));
console.log('Die Distanz beträgt: ', getDistance({ x: 1, y: 1 }, { x: 5, y: 1 }));
</script>
</body>
</html>
@@ -1,92 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 3: Profilcard mit destructuring</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 3: Profilcard mit destructuring</h2>
<p>
Erstelle eine Funktion namens <code>createProfileCard</code>, die die Informationen einer Person
entgegennimmt und daraus eine Bootstrap Card im HTML-Format generiert. Nutze dabei die generatePersonData
Funktion, um die Personendaten zu formatieren. Die Funktion soll so angepasst werden, dass sie Destructuring
für die übergebenen Parameter verwendet.
</p>
</div>
<div class="output alert alert-secondary my-3 row"></div>
</div>
</main>
<script>
'use strict';
const outputEl = document.querySelector('.output');
const createProfileCard = (
person = {
// Default Objekt, falls kein Objekt übergeben wurde
firstName: 'firstName',
lastName: 'LastName',
age: 30,
hobbies: ['Hobby 1', 'Hobby 2', 'Hobby 3'],
},
) => {
// if (typeof person === 'undefined') {
// person = {
// // Default Objekt, falls kein Objekt übergeben wurde
// firstName: 'firstName',
// lastName: 'LastName',
// age: 30,
// hobbies: ['Hobby 1', 'Hobby 2', 'Hobby 3'],
// };
// }
// Desctructuring von person Objelt
const { firstName, lastName, age, hobbies = [] } = person;
const html = `
<div class="col-12 col-sm-6 col-md-4">
<div class="card mb-3">
<img src="https://dummyimage.com/300x150.jpg&text=${firstName}+${lastName}" class="card-img-top" alt="${firstName} ${lastName}" />
<div class="card-body">
<h5 class="card-title">${firstName} ${lastName}</h5>
${age ? `<p class="card-text">${firstName} ${lastName} is ${age} years old.</p>` : ''}
</div>
${
hobbies.length > 0
? `<div class="card-body">
<h5 class="card-title">Hobbies:</h5>
</div>
<ul class="list-group list-group-flush">
${hobbies
.map((hobby) => {
return `<li class="list-group-item">${hobby}</li>`;
})
.join('')}
</ul>
</div>`
: ''
}
<!-- ▲ /card ▲ -->
</div>
`;
return html;
};
const personObj = { firstName: 'John', lastName: 'Wick', age: 51, hobbies: ['guns', 'dogs', 'cars'] };
const person2 = { firstName: 'Jane', lastName: 'Doe', age: 23 };
const person3 = { firstName: 'Joe', lastName: 'Doe' };
outputEl.innerHTML = createProfileCard(personObj);
outputEl.innerHTML += createProfileCard(person2);
outputEl.innerHTML += createProfileCard(person3);
outputEl.innerHTML += createProfileCard();
</script>
</body>
</html>
@@ -1,77 +0,0 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 4: Button Countdown mit Settings</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 4: Button Countdown mit Settings</h2>
<p>
Entwickle einen funktionalen Button, der nach einem Klick einen Countdown in der Schaltfläche anzeigt und
nach Ablauf des Countdowns automatisch wieder aktiviert wird.
</p>
<h4>Szenario</h4>
<p>
Du arbeitest als Frontend-Entwickler für ein Unternehmen, das Online-Formulare für Messeaufträge anbietet.
Um sicherzustellen, dass Benutzer die Formulare nicht versehentlich oder mehrfach absenden, soll ein Button
implementiert werden, der nach dem Absenden für eine bestimmte Zeit (z.B. 5 Sekunden) deaktiviert wird.
Während dieser Zeit soll ein Countdown in der Schaltfläche angezeigt werden, der die verbleibende Zeit bis
zur Reaktivierung des Buttons anzeigt.
</p>
<h4>Aufgaben</h4>
<ol>
<li>
<strong>HTML-Struktur</strong>: Erstelle einen einfachen HTML-Button mit einer Klasse (z.B. button-send).
</li>
<li>
<strong>JavaScript-Funktionalität</strong>:
<ul>
<li>Implementiere einen Event-Listener für den Klick auf den Button.</li>
<li>Erstelle eine Countdown-Funktion, die beim Klicken auf den Button gestartet wird.</li>
<li>
Während des Countdowns soll der Button deaktiviert und der aktuelle Countdown-Wert in der Schaltfläche
angezeigt werden.
</li>
<li>
Nach Ablauf des Countdowns soll der Button wieder aktiviert und der ursprüngliche Text in der
Schaltfläche wiederhergestellt werden.
</li>
</ul>
</li>
<li>
<strong>Countdown-Anzeige</strong>: Der Countdown soll in der Schaltfläche des Buttons angezeigt werden.
Das Format der Anzeige (z.B. "5...", "4...", "3...") kannst du selbst wählen.
</li>
<li>
<strong>Deaktivierung</strong>: Stelle sicher, dass der Button während des Countdowns deaktiviert ist, um
Mehrfachklicks zu verhindern.
</li>
<li>
<strong>Reaktivierung</strong>: Sobald der Countdown abgelaufen ist, soll der Button automatisch wieder
aktiviert werden.
</li>
<li>
<strong>Countdown-Wert konfigurierbar machen</strong>: Ermögliche es, den Countdown-Wert (z.B. 5 Sekunden)
über ein Settings-Objekt einzustellen. aktiviert werden.
</li>
</ol>
<p><strong>Viel Erfolg bei der Umsetzung!</strong></p>
</div>
<button class="btn btn-dark button-send">Click</button>
</div>
</main>
<script>
'use strict';
</script>
</body>
</html>
@@ -1,59 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 5: Summe einer Zahlenreihe rekursiv berechnen</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 5: Summe einer Zahlenreihe rekursiv berechnen</h2>
<p>
Schreibe eine rekursive Funktion in JavaScript, die die Summe aller Zahlen von <code>n</code> bis
<code>1</code> berechnet.
</p>
<h4>Hinweise</h4>
<ul>
<li>Definiere einen Basisfall, der die Rekursion beendet.</li>
<li>Der rekursive Fall sollte das Problem in ein kleineres Teilproblem zerlegen.</li>
</ul>
<p><strong>Viel Erfolg bei der Umsetzung!</strong></p>
</div>
</div>
</main>
<script>
'use strict';
const sumRecursive = (n) => {
if (n === 0) {
return 0;
}
return n + sumRecursive(n - 1); // 5 + 4 + 3 + 2 + 1 + 0
};
const sumReduce = (n) => {
return _.range(0, n + 1).reduce((a, b) => a + b, 0);
};
// Test Cases
console.log(_.range(5)); // => [0,1,2,3,4]
console.log(_.range(2, 5)); // => [2,3,4]
console.log(_.range(2, 10, 2)); // => [2,4,6,8]
console.time('recursive');
console.log(sumRecursive(5)); // => 15 (5 + 4 + 3 + 2 + 1)
console.timeEnd('recursive');
console.time('reduce');
console.log(sumReduce(5)); // => 15 (5 + 4 + 3 + 2 + 1)
console.timeEnd('reduce');
console.log(sumRecursive(10)); // => 55 (10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1)
console.log(sumRecursive(0)); // => 0
</script>
</body>
</html>
@@ -1,59 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Optionale Übung 6: Berechnung von Kombinationen mit Rekursion</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-warning">
<h2>Optionale Übung 6: Berechnung von Kombinationen mit Rekursion</h2>
<p>
Implementiere eine rekursive Funktion in JavaScript, die die Anzahl der Kombinationen berechnet, in denen
man <code>k</code> Elemente aus einer Menge von <code>n</code> Elementen auswählen kann (also den
Binomialkoeffizienten).
</p>
<h4>Hinweise</h4>
<ul>
<li>
Die Formel für Kombinationen lautet:<br /><img
src="https://trainers.atp.wpicert.org/system/wpi_curriculum/file/images/files/000/016/028/302-59/79ca8a079d2c6c737780cd08584c343e.png?1755753490"
class="img-thumbnail"
alt="" />
</li>
<li>
Definiere geeignete Basisfälle, zum Beispiel wenn <code>k</code> gleich <code>0</code> oder
<code>n</code> ist.
</li>
</ul>
</div>
</div>
</main>
<script>
'use strict';
const combinations = (n, k) => {
if (k === 0 || k === n) {
return 1;
}
if (k > n) {
return 0;
}
return combinations(n - 1, k - 1) + combinations(n - 1, k);
};
// Test Cases
console.log(combinations(5, 2)); // => 10
console.log(combinations(6, 3)); // => 20
console.log(combinations(4, 0)); // => 1
console.log(combinations(4, 4)); // => 1
console.log(combinations(5, 6)); // => 0
</script>
</body>
</html>
@@ -1,44 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 7: Rekursive Umkehrung eines Strings</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 7: Rekursive Umkehrung eines Strings</h2>
<p>Schreibe eine rekursive Funktion in JavaScript, die einen gegebenen String umkehrt.</p>
</div>
</div>
</main>
<script>
'use strict';
const reverseString = (str) => {
// Basisfall
if (str.length < 1) {
return '';
}
// console.log('str.slice(1): ', str.slice(1));
return reverseString(str.slice(1)) + str[0];
// return '' + 'o' fn("o") + "l" <-- fn("lo") + "l" <--- fn("llo") + "e" <-- fn("ello") + "h"
};
const reverseString2 = (str) => {
return str.split('').reverse().join('');
};
// Test cases
console.log(reverseString('hello')); // => "olleh"
console.log(reverseString('Recursion')); // => "noisruceR"
console.log(reverseString('')); // => ""
console.log(reverseString('A')); // => "A"
</script>
</body>
</html>
@@ -1,70 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 8: Rekursive Suche des Maximums in einem Array</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 8: Rekursive Suche des Maximums in einem Array</h2>
<p>
Schreibe eine rekursive Funktion in JavaScript, die das größte Element in einem Array von Zahlen findet.
</p>
</div>
</div>
</main>
<script>
'use strict';
const findMax2 = (ar) => {
if (ar.length === 0) return null;
if (ar.length === 1) return ar[0];
let max = ar[0];
let i = -1;
while (++i < ar.length) {
if (ar[i] > max) {
max = ar[i];
}
}
return max;
};
const findMax = (arr) => {
// Basisfall
if (arr.length === 0) {
return null;
}
if (arr.length === 1) {
return arr[0];
}
return Math.max(arr[0], findMax(arr.slice(1))); // Rekursion
// return arr.length === 0 ? null : arr.length === 1 ? arr[0] : Math.max(arr[0], findMax(arr.slice(1)));
};
// Test cases
console.time('rekursion max');
console.log(findMax([1, 5, 3])); // => 5
console.timeEnd('rekursion max');
console.time('Math.max');
console.log(Math.max(...[1, 5, 3]));
console.timeEnd('Math.max');
console.time('for');
console.log(findMax2([1, 5, 3]));
console.timeEnd('for');
console.log(findMax([1, 5, 3, 9, 2])); // => 9
console.log(findMax([-10, -20, -3, -4])); // => -3
console.log(findMax([42])); // => 42
console.log(findMax([])); // => null
</script>
</body>
</html>
@@ -1,148 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 9: Tiefste Ebene eines verschachtelten Arrays finden</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-warning">
<h2>Übung 9 (advanced): Tiefste Ebene eines verschachtelten Arrays finden</h2>
<p>
Schreibe eine rekursive Funktion in JavaScript, die die tiefste Ebene eines verschachtelten Arrays bestimmt.
Die Funktion soll die maximale Verschachtelungstiefe des Arrays zurückgeben.
</p>
</div>
</div>
</main>
<script>
'use strict';
const findDeepestLevel = (arr, currentLevel = 1) => {
if (arr.length === 0) {
return currentLevel;
}
let maxLevel = currentLevel;
// Array durchlaufen
for (let i = 0; i < arr.length; i++) {
// wenn element array
if (Array.isArray(arr[i])) {
/* currentlevel um eins erhöhen und rekursiv wieder aufrufen und neue tiefe ermitteln. Wenn der letzte Aufruf von findD... abgeschlossen wird, wird die dort ermittelte Tiefe zurückgegeben usw...*/
const depth = findDeepestLevel(arr[i], currentLevel + 1);
// wenn tiefe höher als momentan max Tiefe, neue tiefe setzen
if (depth > maxLevel) {
maxLevel = depth;
}
}
}
// neue tiefe zurückgeben
return maxLevel;
};
const findDeepestLevel2 = (arr, currentLevel = 1) => {
if (arr.length === 0) {
return currentLevel;
}
let maxLevel = currentLevel;
// Array durchlaufen
arr.forEach((item) => {
if (Array.isArray(item)) {
const depth = findDeepestLevel2(item, ++currentLevel); // Rekursion
if (depth > maxLevel) {
maxLevel = depth;
}
}
});
// neue tiefe zurückgeben
return maxLevel;
};
const numbers = [
1, //
[
2, //
[3],
],
[1],
];
console.log(numbers[0]); // => 1
console.log(numbers[2]); // => [1]
console.log(numbers[2][0]); // => 1
const data = [
'wert', //
[
'wert', //
'wert',
'wert',
[
'wert', //
'wert',
[
'wert', //
'wert',
['wert'],
],
],
],
];
console.log(findDeepestLevel(data)); // => 5
console.log(findDeepestLevel2(data)); // => 5
console.log(findDeepestLevel([1, [2, [3]], [1]])); // => 3
// const findDeepestLevelIte = (arr) => {
// if (arr.length === 0) {
// return 1;
// }
// console.log('Länge des Arrays: ', arr.length);
// let depth = 0;
// for (let i = 0; i < arr.length; i++) {
// // console.log('i: ', i, ' arr.length: ', arr.length);
// if (Array.isArray(arr[i])) {
// depth++;
// console.log('depth wird erhöht: ', depth);
// } else {
// console.log('kein Array');
// }
// }
// return depth;
// };
// Test cases
console.log(findDeepestLevel([1, [2, [3]], [1]])); // => 3
console.log(findDeepestLevel([1, [2, [3, [4]], 5]])); // => 4
console.log(findDeepestLevel([1, 2, 3, 4, 5])); // => 1
// console.log(findDeepestLevel([])); // => 1
// console.log(findDeepestLevel([1, [2], [3, [4, [5]]]])); // => 4
// console.log(findDeepestLevel([1, [2, [3]], [4, [5, [6]]]])); // => 4
// const $on = (el, ev, fn) => {
// Array.isArray(el) ? el.forEach((ae) => $on(ae, ev, fn)) : el.addEventListener(ev, fn);
// return el;
// };
// $on(Array.from(document.querySelectorAll('li')), 'click', (e) => {
// console.log('click');
// });
// Array.from(document.querySelectorAll('li')).forEach((el) => {
// el.addEventListener('click', (e) => {
// console.log('click');
// });
// });
</script>
</body>
</html>
@@ -1,53 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 10: Summe aller Zahlen in einem verschachtelten Array</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 10: Summe aller Zahlen in einem verschachtelten Array</h2>
<p>
Schreibe eine rekursive Funktion in JavaScript, die die Summe aller Zahlen in einem verschachtelten Array
berechnet. Das Array kann beliebig tief verschachtelt sein und enthält nur Zahlen oder weitere Arrays.
</p>
</div>
</div>
</main>
<script>
'use strict';
const sumNestedArray = (arr) => {
// Basisfall: Wenn das Array leer ist, ist die Summe 0
if (arr.length === 0) {
return 0;
}
// Nimm das erste Element des Arrays
const first = arr[0];
const rest = arr.slice(1);
let sumFirst = 0;
// Wenn das erste Element ein Array ist, rufe die Funktion rekursiv auf
if (Array.isArray(first)) {
sumFirst = sumNestedArray(first);
} else if (!isNaN(first)) {
// Wenn es eine Zahl ist, füge sie zur Summe hinzu
sumFirst = Number(first);
}
// Rekursiver Fall: Summe des ersten Elements + Summe des restlichen Arrays
return sumFirst + sumNestedArray(rest);
};
// Test cases
console.log(sumNestedArray([1, [2, [3, 4], 5], 6])); // => 21
console.log(sumNestedArray([[[[1]]], 2, [3, [4, [5]]]])); // => 15
console.log(sumNestedArray([])); // => 0
console.log(sumNestedArray([10, [20, [30, [40]]]])); // => 100
console.log(sumNestedArray([1, 'a', [2, 'b', [3, 4]], 5])); // => 15 (ignoriert Nicht-Zahlen)
</script>
</body>
</html>
Binary file not shown.
@@ -1,61 +0,0 @@
// Variante 1
const sentence = 'Dies ist eine Übung um der callback Hölle zu entkommen.';
const printWords = (sentence) => {
const wordArr = sentence.split(' ');
for (let i = 0; i < wordArr.length; i++) {
setTimeout(() => {
console.log(wordArr[i]);
}, 1000 * i);
}
};
const printWordsRek = (sentence, idxWort = 0) => {
const wordArr = sentence.split(' ');
// Basis-Fall
if (idxWort >= wordArr.length) {
return '';
}
// rekursiver mist :)
setTimeout(() => {
printWordsRek(sentence, idxWort + 1);
}, 1000);
// Ausgabe des Wortes
console.log(wordArr[idxWort]);
};
printWords(sentence);
printWordsRek(sentence);
// setTimeout(() => {
// console.log('The');
// setTimeout(() => {
// console.log('pyramid');
// setTimeout(() => {
// console.log('of');
// setTimeout(() => {
// console.log('doom');
// setTimeout(() => {
// console.log('keeps');
// setTimeout(() => {
// console.log('growing.');
// }, 1000);
// }, 1000);
// }, 1000);
// }, 1000);
// }, 1000);
// }, 1000);
// Übung 11: Die Pyramide abbrechen
// Schreibe das Codebeispiel 96 so um, dass keine Pyramide entsteht. Benutze dazu, wie im Text angedeutet, eine Funktion, die das n-te Wort ausgibt und sich per setTimeout(…) mit n + 1 als Parameter aufruft, solange noch Wörter im Satz vorhanden sind.
@@ -1 +0,0 @@
Ich bin file 01
@@ -1 +0,0 @@
Ich bin file 02
@@ -1 +0,0 @@
Ich bin file 03
@@ -1 +0,0 @@
Ich bin file 04
@@ -1 +0,0 @@
Ich bin file 05
@@ -1 +0,0 @@
Ich bin file 06
@@ -1,29 +0,0 @@
// const fs = require('node:fs'); // commonjs
import fs from 'node:fs'; // esm - module Schreibweise
const getFileBy = (path, encoding = 'utf-8') => {
return new Promise((resolve, reject) => {
// async process
fs.readFile(path, encoding, (error, data) => {
if (error) {
reject(error);
}
resolve(data);
});
});
};
Promise.all([
getFileBy('data/file01.txt'),
getFileBy('data/file02.txt'),
getFileBy('data/file03.txt'),
getFileBy('data/file04.txt'),
getFileBy('data/file05.txt'),
getFileBy('data/file06.txt'),
])
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
});
@@ -1,13 +0,0 @@
{
"name": "u12_mehrere-dateien-auslesen",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module"
}
@@ -1,54 +0,0 @@
// const dns = require('node:dns'); // commonjs
import dns from 'node:dns'; // esm module
import util from 'node:util';
import color from 'chalk';
const IP_V = 4; // we use IP protocol version 4
const URL = 'google.de';
const getIpBy = (url, ipVersion = 4) => {
return new Promise((resolve, reject) => {
// async process
dns.lookup(url, ipVersion, (error, address) => {
if (error) {
reject(error);
} else {
resolve({ address: address, family: ipVersion });
}
});
});
};
// Promises Unterobjekt von Node
const getPromisesIpBy = (url, ipVersion = 4) => {
// async process
return dns.promises.lookup(url, ipVersion);
};
// Promisify Helferfunktion
const getPromisifyIpBy = util.promisify(dns.lookup);
// Test Cases:
getIpBy(URL, IP_V)
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(color.red(err));
});
getPromisesIpBy(URL)
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(color.red(err));
});
getPromisifyIpBy(URL, IP_V)
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(color.red(err));
});
-28
View File
@@ -1,28 +0,0 @@
{
"name": "u13_dns-lookup",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "u13_dns-lookup",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"chalk": "^5.6.2"
}
},
"node_modules/chalk": {
"version": "5.6.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz",
"integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==",
"license": "MIT",
"engines": {
"node": "^12.17.0 || ^14.13 || >=16.0.0"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
}
}
}
@@ -1,16 +0,0 @@
{
"name": "u13_dns-lookup",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module",
"dependencies": {
"chalk": "^5.6.2"
}
}
@@ -1,60 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 15: Einkaufsliste bearbeiten</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 15: Einkaufsliste bearbeiten</h2>
<p>
Erstelle eine Einkaufsliste als zweidimensionales Array mit Kategorien und Artikeln. Führe folgende
Änderungen durch:
</p>
<ol class="list">
<li>Entferne das zweite Element aus jeder Kategorie.</li>
<li>Füge jeweils ein neues Element hinzu.</li>
</ol>
</div>
</div>
</main>
<script>
'use strict';
const shoppingList = [
['Fruits', 'Apples', 'Bananas', 'Oranges'],
['Vegetables', 'Carrots', 'Broccoli', 'Spinach'],
['Dairy', 'Milk', 'Cheese', 'Yogurt'],
];
// Your code here
shoppingList[0][2] = 'Grapes';
shoppingList[1][2] = 'Tomatoes';
shoppingList[2][2] = 'Butter';
// Your code here
const changeShoppingList = (arr, changeList = ['Grapes', 'Tomatoes', 'Butter']) => {
return arr.map((elems, idx) => {
elems[2] = changeList[idx];
return elems;
});
};
const newItems = ['Grapes', 'Tomatoes', 'Butter'];
shoppingList.forEach((categories, index) => {
categories.splice(2, 1, newItems[index]);
});
console.log(shoppingList);
console.log(changeShoppingList(shoppingList));
console.log(shoppingList);
</script>
</body>
</html>
@@ -1,48 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 16: Geoquiz</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 16: Geoquiz</h2>
<p>
Eine Schule gibt die Entwicklung eines Geoquiz in Auftrag, bei dem Schüler die Hauptstädte verschiedener
Staaten nennen müssen. Deine Aufgabe besteht in der Entwicklung der Lösungsfunktion
<code>getCapitalOf</code>, die eine Hauptstadt zum übergebenen Staat (<code>country</code>) zurückliefert.
</p>
<ol class="list">
<li>Entferne das zweite Element aus jeder Kategorie.</li>
<li>Füge jeweils ein neues Element hinzu.</li>
</ol>
</div>
</div>
</main>
<script>
'use strict';
const countriesWithCapital = [
['UK', 'London'],
['France', 'Paris'],
['Germany', 'Berlin'],
['Switzerland', 'Bern'],
['Austria', 'Vienna'],
['Russia', 'Moscow'],
];
const getCapitalOf = (country) => {
return countriesWithCapital.find((elemArr) => {
return elemArr[0] === country;
})[1];
};
console.log(getCapitalOf('Switzerland')); // => 'Bern'
</script>
</body>
</html>
@@ -1,70 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 17: Lagerbestand erweitern</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 17: Lagerbestand erweitern</h2>
<p>
Füge eine neue Kategorie <strong>«Books»</strong> zu dem bestehenden dreidimensionalen Lagerbestandssystem
hinzu und trage zwei neue Produkte mit deren Lagerorten und Mengen ein.
</p>
</div>
</div>
</main>
<script>
'use strict';
const inventory = [
[
// Category: Electronics
['Shelf 1', 'Laptop', 10],
['Shelf 2', 'Smartphone', 25],
],
[
// Category: Clothing
['Shelf 1', 'T-Shirts', 50],
['Shelf 2', 'Jeans', 30],
],
[
// Category: Groceries
['Shelf 1', 'Milk', 100],
['Shelf 2', 'Bread', 80],
],
];
// Your code here
inventory.push([
['Shelf 1', 'Novels', 40],
['Shelf 2', 'Non-fiction', 35],
]);
console.log(inventory);
/* Expected outcome:
[
[ // Electronics
['Shelf 1', 'Laptop', 10],
['Shelf 2', 'Smartphone', 25],
],
[ // Clothing
['Shelf 1', 'T-Shirts', 50],
['Shelf 2', 'Jeans', 30],
],
[ // Groceries
['Shelf 1', 'Milk', 100],
['Shelf 2', 'Bread', 80],
],
[ // Books
['Shelf 1', 'Novels', 40],
['Shelf 2', 'Non-fiction', 35],
],
]
*/
</script>
</body>
</html>
@@ -1,67 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 18: 3D Array Zugriff</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 18: 3D Array Zugriff</h2>
<p>
Greife auf das zweite Produkt in der <strong>«Clothing»</strong>-Kategorie zu und ändere die Menge von
<strong>«Jeans»</strong> von 30 auf 25.
</p>
</div>
</div>
</main>
<script>
'use strict';
const inventory = [
[
// Category: Electronics
['Shelf 1', 'Laptop', 10],
['Shelf 2', 'Smartphone', 25],
],
[
// Category: Clothing
['Shelf 1', 'T-Shirts', 50],
['Shelf 2', 'Jeans', 30],
],
[
// Category: Groceries
['Shelf 1', 'Milk', 100],
['Shelf 2', 'Bread', 80],
],
[
// Category: Books
['Shelf 1', 'Novels', 40],
['Shelf 2', 'Non-fiction', 35],
],
];
// Your code here
inventory[1][1][2] -= 5;
inventory[1][1][2] = 25;
console.log(inventory);
/*
Expected outcome:
[
[ // Electronics
['Shelf 1', 'Laptop', 10],
['Shelf 2', 'Smartphone', 25],
],
[ // Clothing
['Shelf 1', 'T-Shirts', 50],
['Shelf 2', 'Jeans', 25], // Changed quantity
],
// ...
]
*/
</script>
</body>
</html>
@@ -1,98 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 19: Bildbearbeitung – Helligkeit erhöhen</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 19: Bildbearbeitung – Helligkeit erhöhen</h2>
<p>
Schreibe eine Funktion <code>increaseBrightness</code>, die die Helligkeit aller Pixel in einem 3D Bildarray
um einen bestimmten Wert erhöht. Stelle sicher, dass die RGB-Werte nicht über <code>255</code> hinausgehen.
</p>
<p>
Die Funktion nimmt ein dreidimensionales Array <code>image</code> und einen Wert <code>value</code> als
Parameter. Ziel ist es, die Helligkeit jedes Pixels im Bild zu erhöhen, indem jeder RGB-Wert um
<code>value</code> erhöht wird. Stelle dabe sicher, dass kein RGB-Wert den maximalen Wert von
<code>255</code> überschreitet.
</p>
</div>
</div>
</main>
<script>
'use strict';
'use strict';
const imageAr = [
[
// Row 1
[100, 150, 200], // Pixel 1
[50, 100, 150], // Pixel 2
],
[
// Row 2
[25, 75, 125], // Pixel 3
[200, 225, 250], // Pixel 4
],
];
const increaseBrightness = (imageAr = [], value) => {
// Your code here
return imageAr.map((row) => {
return row.map((rgbValue) => {
return rgbValue.map((elem) => {
const result = elem + value;
if (result > 255) {
return 255;
}
return result;
});
});
});
};
const increaseBrightness2 = (image, value) => {
const imageAr = image.map((row) => {
const rows = row.map((pixel) => {
const pixels = pixel.map((color) => {
return Math.min(255, color + value);
});
return pixels;
});
return rows;
});
return imageAr;
};
console.time('guard');
const newImage = increaseBrightness(imageAr, 30);
console.log(newImage);
console.timeEnd('guard');
console.time('Math');
const newImage2 = increaseBrightness2(imageAr, 30);
console.log(newImage2);
console.timeEnd('Math');
/*
Expected outcome:
[
[
[130, 180, 230],
[80, 130, 180],
],
[
[55, 105, 155],
[230, 255, 255],
],
]
*/
</script>
</body>
</html>
@@ -1,47 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 20: Geoquiz — Teil 2</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 20: Geoquiz — Teil 2</h2>
<p>
In der erweiterten Ausbaustufe sollen die Schüler den Staat zu einer Hauptstadt nennen. Deine Aufgabe ist es
erneut, eine Lösungsfunktion zu programmieren. Dieses Mal nimmt <code>getCountryForCapital</code> eine
Hauptstadt (<code>capital</code>) entgegen und liefert den zugehörigen Staat zurück.
</p>
<p>
Die Funktion soll auf die bestehende Konstante <code>countriesWithCapital</code> zugreifen. Es ist nicht
erlaubt, die Struktur der Daten in der Konstante zu ändern.
</p>
</div>
</div>
</main>
<script>
'use strict';
const countriesWithCapital = [
['UK', 'London'],
['France', 'Paris'],
['Germany', 'Berlin'],
['Switzerland', 'Bern'],
['Austria', 'Vienna'],
['Russia', 'Moscow'],
];
const getCountryFor = (capital) => {
return countriesWithCapital.find((elemArr) => {
return elemArr[1] === capital;
})[0];
};
console.log(getCountryFor('Paris')); // => 'France'
</script>
</body>
</html>
@@ -1,75 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 21: Pokémon — Evolution</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 21: Pokémon — Evolution</h2>
<p>
Kennst du Pokémon? Allen Pokémon-Spielen ist gemein, dass es Pokémon (Phantasiewesen) gibt, die über
verschiedene Evolutionsstufen verfügen. Ein Pokémon kann sich bis zu zweimal weiterentwickeln. D. h. es gibt
maximal drei Stufen: seine Anfangsstufe und bis zu zwei Folgestufen. Jede dieser Stufen trägt einen neuen
Pokémon-Namen — keiner dieser Namen kann doppelt vorkommen. Einen guten Überblick über die Stufen bei
Pokémon GO findest du auf <a href="https://pokemondb.net/evolution">https://pokemondb.net/evolution</a>.
</p>
<ol class="list">
<li>
Schreibe eine Funktion <code>stagesFor</code>, der du eine Pokémon-Evolutionsstufe übergibst und die dir
alle dazugehörigen Evolutionsstufen als Array zurückliefert. Als Daten verwendest du exemplarisch die
Evolutionsstufen von Pidgey, Vulpix und Dratini.
</li>
<li>
Entwickle die Funktionen <code>stagesAfter</code> und <code>stagesBefore</code>, die dir nur die Stufen
vor bzw. nach der angefragten Stufe zurückliefern.
</li>
</ol>
</div>
</div>
</main>
<script>
'use strict';
const evolutionStages = [
['Pidgey', 'Pidgeotto', 'Pidgeot'],
['Vulpix', 'Ninetales'],
['Dratini', 'Dragonair', 'Dragonite'],
];
const stagesFor = (pokemon) => {
const stages = evolutionStages.find((stages) => stages.includes(pokemon));
if (!stages) {
console.warn('stages not found');
return [];
}
return stages; // wenn unfedined leeres array zurückgeben
};
const stagesAfter = (pokemon) => {
const stages = stagesFor(pokemon);
return stages.slice(stages.indexOf(pokemon) + 1);
};
const stagesBefore = (pokemon) => {
const stages = stagesFor(pokemon);
return stages.slice(0, stages.indexOf(pokemon));
};
console.log(stagesFor('Vulpix')); // => [ 'Vulpix', 'Ninetales' ]
console.log(stagesAfter('Anton')); // =>
console.log(stagesAfter('Dratini')); // => [ 'Dragonair', 'Dragonite' ]
console.log(stagesBefore('Pidgeot')); // => [ 'Pidgey', 'Pidgeotto' ]
console.log(stagesBefore('Dragonair')); // => [ 'Dratini' ]
console.log(stagesBefore('Pidgey')); // => [ ]
console.log(stagesBefore('Pidgeot')); // => ['Pidgey', 'Pidgeotto']
</script>
</body>
</html>
@@ -1,91 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 22: Fröhliches Mixen mit Arrays</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 22: Fröhliches Mixen mit Arrays</h2>
<p>
Du möchtest mal wieder Cocktails mixen. Aber heute konntest du dich nicht so recht für einen bestimmten
Cocktail entscheiden. Am besten wäre es, wenn du aus mehreren Rezepten herausfinden könntest, für welches du
die passenden Zutaten vorrätig hast. Nun wird es etwas kniffliger, denn du benötigst ein Array, das die
Rezepte wiederum in Form von Arrays aus Zutaten enthält.
</p>
<p>Die Konsole soll die Zutaten des ersten gefundenen Cocktails loggen.</p>
</div>
</div>
</main>
<script>
'use strict';
const honoluluFlip = [
'Maracuja Juice', //
'Pineapple Juice',
'Lemon Juice',
'Grapefruit Juice',
'Crushed Ice',
];
const casualFriday = [
'Vodka', //
'Lime Juice',
'Apple Juice',
'Cucumber',
];
const pinkDolly = [
'Vodka', //
'Orange Juice',
'Pineapple Juice',
'Grenadine',
'Cream',
'Coco Syrup',
];
const cocktailRecipes = [honoluluFlip, casualFriday, pinkDolly];
const AVAILABLE_INGREDIENTS = [
'Pineapple',
'Maracuja Juice',
'Cream',
'Grapefruit Juice',
'Crushed Ice',
'Milk',
'Vodka',
'Apple Juice',
'Aperol',
'Pineapple Juice',
'Lime Juice',
'Lemons',
'Cucumber',
];
const isMixableWithMyIngredients = (cocktailRecipe) => {
return isMixableWith(cocktailRecipe, AVAILABLE_INGREDIENTS);
};
const isMixableWith = (cocktailRecipe, availableIngredients) => {
return cocktailRecipe.every((ingredientFromRecipe) =>
hasIngredient(availableIngredients, ingredientFromRecipe),
);
};
const hasIngredient = (listAr, searchStr) => {
return listAr.includes(searchStr);
};
console.log(cocktailRecipes);
console.log('isMixable: ', isMixableWith(casualFriday, AVAILABLE_INGREDIENTS));
console.log(
cocktailRecipes.find((recipeAr) => {
return isMixableWithMyIngredients(recipeAr);
}),
);
// => [ 'Vodka', 'Lime Juice', 'Apple Juice', 'Cucumber' ]
</script>
</body>
</html>
@@ -1,68 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 23: Fetch API – Einfache Datenabfrage</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 23: Fetch API – Einfache Datenabfrage</h2>
<p>
Erstelle eine Funktion <code>fetchUsers</code>, die mithilfe der Fetch API eine Liste von Benutzern von der
DummyJSON-API abruft. Verwende async/await und try/catch, um Netzwerkfehler abzufangen. Die abgerufenen
Daten sollen dann in der Konsole ausgegeben werden.
</p>
<p>
<strong>Hinweis:</strong> Verwende die URL
<a href="https://dummyjson.com/users">https://dummyjson.com/users</a> für den Fetch-Aufruf.
</p>
</div>
<div class="output alert alert-secondary my-3"></div>
</div>
</main>
<script>
'use strict';
const outputEl = document.querySelector('.output');
const fetchUsers = async () => {
try {
// Fetch-aufruf an die API
const response = await fetch('https://dummyjson.com/users');
// Prüfen ob die OK ist
if (!response.ok) {
throw new Error(`HTTP-Fehler: ${response.status}`);
}
// JSON-Daten parsen
const data = await response.json();
return data;
return data;
} catch (error) {
console.error(error.message);
}
};
// Funktionsaufruf
fetchUsers().then((data) => {
console.log(data);
console.log(data.users.length);
outputEl.innerHTML = '';
data.users.forEach((user) => {
const { firstName, lastName, email } = user;
console.log(`${firstName} ${lastName} (${email})`);
outputEl.innerHTML += `${firstName} ${lastName} (${email})<br />`;
});
});
</script>
</body>
</html>
@@ -1,55 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 24: Objekt in JSON umwandeln</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 24: Objekt in JSON umwandeln</h2>
<p>
Gegeben ist ein JavaScript-Objekt <code>book</code>. Konvertiere dieses Objekt in einen JSON-String und
parse anschließend die Zeichenkette zurück in ein JavaScript-Objekt. Gib den Titel und den Autor des Buches
in der Konsole aus.
</p>
<p>Folgendes sollte in der Konsole ausgegeben werden:</p>
<code>
<pre>
// JSON-String
{"title":"The Great Gatsby","author":"F. Scott Fitzgerald","year":1925}
// JavaScript Object
The Great Gatsby
F. Scott Fitzgerald
</pre>
</code>
</div>
</div>
</main>
<script>
'use strict';
const book = {
title: 'The Great Gatsby',
author: 'F. Scott Fitzgerald',
year: 1925,
};
// JSON String
const bookStr = JSON.stringify(book, '', 2);
console.log(bookStr);
// JS Object
const bookObj = JSON.parse(bookStr);
console.log(bookObj.title); // => 'The Great Gatsby'
console.log(bookObj.author); // => 'F. Scott Fitzgerald'
</script>
</body>
</html>
@@ -1,15 +0,0 @@
## Übung 25: CSV-Datensätze mit Anführungszeichen
Bisher haben wir die Felder in einem CSV-Datensatz einfach mit der Anweisung:
```js
record.split(',');
```
in einzelne Felder zerlegt. In der Praxis kann es aber vorkommen, dass ein einzelnes Feld ein Komma enthält. Das Problem wird üblicherweise gelöst, indem die einzelnen Felder noch mit Anführungszeichen umgeben werden. Hier ist ein Beispiel:
```js
'very big, soft computer mouse', 'the cutest peripheral ever', '10', '39.90';
```
Das erste Feld enthält ein Komma (very big, soft computer mouse), trotzdem ist die Unterteilung eindeutig. Schreibe ein kurzes Programm, das diesen Datensatz korrekt zerlegt und die einzelnen Felder ausgibt:
@@ -1,14 +0,0 @@
const csvStr = "'very big, soft computer mouse', 'the cutest peripheral ever', '10', '39.90'";
console.log(csvStr.slice(1, csvStr.length - 1).split(/', '/));
// Übung 25: CSV-Datensätze mit Anführungszeichen
// Bisher haben wir die Felder in einem CSV-Datensatz einfach mit der Anweisung:
// record.split(',')
// in einzelne Felder zerlegt. In der Praxis kann es aber vorkommen, dass ein einzelnes Feld ein Komma enthält. Das Problem wird üblicherweise gelöst, indem die einzelnen Felder noch mit Anführungszeichen umgeben werden. Hier ist ein Beispiel:
// 'very big, soft computer mouse', 'the cutest peripheral ever', '10', '39.90'
// Das erste Feld enthält ein Komma (very big, soft computer mouse), trotzdem ist die Unterteilung eindeutig. Schreibe ein kurzes Programm, das diesen Datensatz korrekt zerlegt und die einzelnen Felder ausgibt:
@@ -1,51 +0,0 @@
# Regex Beispiel
Am besten löst man das mit einem regulären Ausdruck, der entweder nach **Inhalten in Anführungszeichen** sucht _oder_ nach **Inhalten ohne Kommas**.
Hier ist der passende Reguläre Ausdruck:
`/"([^"\\]*(?:\\.[^"\\]*)*)"|([^,]+)/g`
---
### Wie der Regex funktioniert
Der Ausdruck nutzt das **ODER-Prinzip (`|`)**, um zwei Szenarien zu matchen:
1. **`"([^"\\]*(?:\\.[^"\\]*)*)"` (Gruppe 1):** Matcht alles, was in doppelten Anführungszeichen steht. Er erlaubt sogar escaped Anführungszeichen (`\"`) im Text.
2. **`([^,]+)` (Gruppe 2):** Wenn keine Anführungszeichen da sind, matcht er alles bis zum nächsten Komma.
---
### Anwendung in JavaScript (Beispiel)
Da du das Ergebnis sicherlich in einem Array von einzelnen Werten brauchst, kannst du den Regex wie folgt anwenden. Hierbei nutzen wir `matchAll`, um die Treffer sauber zu trennen und die Anführungszeichen direkt zu entfernen:
```javascript
const input = '"very big, soft computer mouse","the cutest peripheral ever",10,39.90';
const regex = /"([^"\\]*(?:\\.[^"\\]*)*)"|([^,]+)/g;
const matches = [...input.matchAll(regex)];
const result = matches.map((match) => {
// Wenn Gruppe 1 existiert, war es ein String in Anführungszeichen
// Wenn Gruppe 2 existiert, war es ein unberührter Wert (Zahl)
const value = match[1] !== undefined ? match[1] : match[2].trim();
// Optional: Datentypen konvertieren
if (!isNaN(value) && value !== '') {
return Number(value);
}
return value;
});
console.log(result);
```
### Das Ergebnis (Output)
Nach dem Parsen erhältst du ein sauberes Array, bei dem die Kommas innerhalb der Strings ignoriert wurden und die Zahlen einsatzbereit sind:
```json
["very big, soft computer mouse", "the cutest peripheral ever", 10, 39.9]
```
@@ -1 +0,0 @@
"very big, soft computer mouse","the cutest peripheral ever",10,39.90
1 very big, soft computer mouse the cutest peripheral ever 10 39.90
@@ -1,11 +0,0 @@
Code,Short Description,Tagline,Quantity,Price
MUG0007,coffee mug with LCD level indicator,never again reach for the empty mug,20,49.90
MUG0013,coffee mug with bluetooth-connected coffee grounds scanner for automatized fortune telling,put the smart into coffee reading,20,99.90
OFF3145,pen with pre-warmed ink (tested on the South Pole),the pen is mightier than the cold,50,29.90
COM1001,ambidextrous computer mouse,end the dictate of left and right,10,19.90
COM0404,Easter egg themed webcam for your monitor,put an Easter egg on hardware too,20,149.90
COM0001,Vulcan language vi cheatsheet,learn vi and Vulcan at the same time,3,9.90
COM1536,Klingon language emacs cheatsheet,learn emacs and Klingon at the same time,50,9.90
MOB0555,smartphone case with built-in screen,never miss a message,20,39.90
1 Code Short Description Tagline Quantity Price
2 MUG0007 coffee mug with LCD level indicator never again reach for the empty mug 20 49.90
3 MUG0013 coffee mug with bluetooth-connected coffee grounds scanner for automatized fortune telling put the smart into coffee reading 20 99.90
4 OFF3145 pen with pre-warmed ink (tested on the South Pole) the pen is mightier than the cold 50 29.90
5 COM1001 ambidextrous computer mouse end the dictate of left and right 10 19.90
6 COM0404 Easter egg themed webcam for your monitor put an Easter egg on hardware too 20 149.90
7 COM0001 Vulcan language vi cheatsheet learn vi and Vulcan at the same time 3 9.90
8 COM1536 Klingon language emacs cheatsheet learn emacs and Klingon at the same time 50 9.90
9 MOB0555 smartphone case with built-in screen never miss a message 20 39.90
@@ -1,58 +0,0 @@
import fs from 'node:fs';
import color from 'chalk';
const data = fs.readFileSync('data/products.csv', 'utf-8');
const productAr = data.split('\n').map((row) => row.replace('\n', ''));
const headerAr = productAr.shift().split(/\s*,\s*/);
console.log(productAr);
// console.log(headerAr);
// console.log('=======');
// console.log(productAr);
const convertCsvToJson = (products, headerAr) => {
let jsonStr = '[\n';
products.forEach((row, idxRow) => {
jsonStr += ' {\n';
row
.trim()
.split(',')
.forEach((elem, idxElem, ar) => {
if (ar.length === idxElem + 1) {
if (isNaN(elem)) {
jsonStr += ` "${headerAr[idxElem]}": "${elem}"\n`;
} else {
jsonStr += ` "${headerAr[idxElem]}": ${Number(elem)}\n`;
}
} else {
if (isNaN(elem)) {
jsonStr += ` "${headerAr[idxElem]}": "${elem}",\n`;
} else {
jsonStr += ` "${headerAr[idxElem]}": ${Number(elem)},\n`;
}
}
});
if (products.length === idxRow + 1) {
jsonStr += ` }\n`;
} else {
jsonStr += ` },\n`;
}
});
jsonStr += ']';
console.log(color.yellow(`${jsonStr}`));
fs.writeFile('products.json', jsonStr, 'utf-8', (err) => {
if (err) {
console.log(err);
} else {
console.log(color.green('file created!'));
}
});
};
convertCsvToJson(productAr, headerAr);
@@ -1,21 +0,0 @@
import fs from 'node:fs';
import papa from 'papaparse';
//https://www.npmjs.com/package/papaparse
const data = fs.readFileSync('data/csvDatei.csv', 'utf-8').trim();
const parsed = papa.parse(data, {
dynamicTyping: true,
});
const dataRow = parsed.data[0];
const result = {
name: dataRow[0],
description: dataRow[1],
quantity: dataRow[2],
price: dataRow[3],
};
console.log(JSON.stringify(result, null, 2));
@@ -1,62 +0,0 @@
import fs from 'node:fs';
import color from 'chalk';
const data = fs.readFileSync('data/products.csv', 'utf-8');
const toCamelCase = (str) => {
return str
.trim()
.toLowerCase()
.replace(/[^a-zA-Z0-9]+(.)/g, (match, chr) => chr.toUpperCase());
};
const convertCsvToJson = (products, ar) => {
const resultAr = products.map((str) => {
const fields = str.split(/\s*,\s*/);
const labels = ar.map((label, idx) => {
return [label, isNaN(fields[idx]) ? fields[idx] : Number(fields[idx])];
});
const obj = Object.fromEntries(labels);
// console.log(labels); // Entries Array
//console.log(obj);
return obj;
// return {
// [ar[0]]: fields[0],
// [ar[1]]: fields[1],
// [ar[2]]: fields[2],
// [ar[3]]: Number(fields[3]),
// [ar[4]]: Number(fields[4]),
// };
});
// console.log(resultAr);
const jsonStr = JSON.stringify(resultAr, '', 2);
fs.writeFile('products.json', jsonStr, 'utf-8', (err) => {
if (err) {
console.log(err);
} else {
console.log(color.green('file created!'));
}
});
};
const productAr = data
.split('\n')
.map((row) => row.replace('\n', ''))
.filter((row) => row !== '');
const headerAr = productAr
.shift()
.split(/\s*,\s*/)
.map(toCamelCase);
// console.log('=======');
// console.log(productAr);
convertCsvToJson(productAr, headerAr);
@@ -1,23 +0,0 @@
// Übung 26: CSV-Datensätze mit Anführungszeichen — Teil 2
// In der Praxis finden sich auch CSV-Datensätze, in denen manche Felder mit Anführungszeichen umgeben sind und manche nicht.
// Schreibe ein Programm, das auch mit diesen Fällen zurechtkommt. Folgender Datensatz soll korrekt zerlegt werden:
const mixedCSV = '"very big, soft computer mouse","the cutest peripheral ever",10,39.90';
const regex = /"([^"\\]*(?:\\.[^"\\]*)*)"|([^,]+)/g;
const matches = [...mixedCSV.matchAll(regex)];
const result = matches.map((match) => {
// Wenn Gruppe 1 existiert, war es ein String in Anführungszeichen
// Wenn Gruppe 2 existiert, war es ein unberührter Wert (Zahl)
const value = match[1] !== undefined ? match[1] : match[2].trim();
// Optional: Datentypen konvertieren
if (!isNaN(value) && value !== '') {
return Number(value);
}
return value;
});
console.log(result);
-35
View File
@@ -1,35 +0,0 @@
{
"name": "u26_csv-quotes2",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "u26_csv-quotes2",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"chalk": "^5.6.2",
"papaparse": "^5.5.4"
}
},
"node_modules/chalk": {
"version": "5.6.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz",
"integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==",
"license": "MIT",
"engines": {
"node": "^12.17.0 || ^14.13 || >=16.0.0"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/papaparse": {
"version": "5.5.4",
"resolved": "https://registry.npmjs.org/papaparse/-/papaparse-5.5.4.tgz",
"integrity": "sha512-SwzWD9gl/ElwYLCI0nUja1mFJzjq2D8ziShfNBa7zCHzkOozeOGDwHWQ+tvCzEZcewecWZ5U7kUopDnG+DFYEQ==",
"license": "MIT"
}
}
}
@@ -1,17 +0,0 @@
{
"name": "u26_csv-quotes2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module",
"dependencies": {
"chalk": "^5.6.2",
"papaparse": "^5.5.4"
}
}
@@ -1,58 +0,0 @@
[
{
"code": "MUG0007",
"shortDescription": "coffee mug with LCD level indicator",
"tagline": "never again reach for the empty mug",
"quantity": 20,
"price": 49.9
},
{
"code": "MUG0013",
"shortDescription": "coffee mug with bluetooth-connected coffee grounds scanner for automatized fortune telling",
"tagline": "put the smart into coffee reading",
"quantity": 20,
"price": 99.9
},
{
"code": "OFF3145",
"shortDescription": "pen with pre-warmed ink (tested on the South Pole)",
"tagline": "the pen is mightier than the cold",
"quantity": 50,
"price": 29.9
},
{
"code": "COM1001",
"shortDescription": "ambidextrous computer mouse",
"tagline": "end the dictate of left and right",
"quantity": 10,
"price": 19.9
},
{
"code": "COM0404",
"shortDescription": "Easter egg themed webcam for your monitor",
"tagline": "put an Easter egg on hardware too",
"quantity": 20,
"price": 149.9
},
{
"code": "COM0001",
"shortDescription": "Vulcan language vi cheatsheet",
"tagline": "learn vi and Vulcan at the same time",
"quantity": 3,
"price": 9.9
},
{
"code": "COM1536",
"shortDescription": "Klingon language emacs cheatsheet",
"tagline": "learn emacs and Klingon at the same time",
"quantity": 50,
"price": 9.9
},
{
"code": "MOB0555",
"shortDescription": "smartphone case with built-in screen",
"tagline": "never miss a message",
"quantity": 20,
"price": 39.9
}
]
Binary file not shown.
@@ -1,51 +0,0 @@
# Regex Beispiel
Am besten löst man das mit einem regulären Ausdruck, der entweder nach **Inhalten in Anführungszeichen** sucht _oder_ nach **Inhalten ohne Kommas**.
Hier ist der passende Reguläre Ausdruck:
`/"([^"\\]*(?:\\.[^"\\]*)*)"|([^,]+)/g`
---
### Wie der Regex funktioniert
Der Ausdruck nutzt das **ODER-Prinzip (`|`)**, um zwei Szenarien zu matchen:
1. **`"([^"\\]*(?:\\.[^"\\]*)*)"` (Gruppe 1):** Matcht alles, was in doppelten Anführungszeichen steht. Er erlaubt sogar escaped Anführungszeichen (`\"`) im Text.
2. **`([^,]+)` (Gruppe 2):** Wenn keine Anführungszeichen da sind, matcht er alles bis zum nächsten Komma.
---
### Anwendung in JavaScript (Beispiel)
Da du das Ergebnis sicherlich in einem Array von einzelnen Werten brauchst, kannst du den Regex wie folgt anwenden. Hierbei nutzen wir `matchAll`, um die Treffer sauber zu trennen und die Anführungszeichen direkt zu entfernen:
```javascript
const input = '"very big, soft computer mouse","the cutest peripheral ever",10,39.90';
const regex = /"([^"\\]*(?:\\.[^"\\]*)*)"|([^,]+)/g;
const matches = [...input.matchAll(regex)];
const result = matches.map((match) => {
// Wenn Gruppe 1 existiert, war es ein String in Anführungszeichen
// Wenn Gruppe 2 existiert, war es ein unberührter Wert (Zahl)
const value = match[1] !== undefined ? match[1] : match[2].trim();
// Optional: Datentypen konvertieren
if (!isNaN(value) && value !== '') {
return Number(value);
}
return value;
});
console.log(result);
```
### Das Ergebnis (Output)
Nach dem Parsen erhältst du ein sauberes Array, bei dem die Kommas innerhalb der Strings ignoriert wurden und die Zahlen einsatzbereit sind:
```json
["very big, soft computer mouse", "the cutest peripheral ever", 10, 39.9]
```
@@ -1 +0,0 @@
"very big, soft computer mouse","the cutest peripheral ever",10,39.90
1 very big, soft computer mouse the cutest peripheral ever 10 39.90
@@ -1,11 +0,0 @@
Code,Short Description,Tagline,Quantity,Price
MUG0007,coffee mug with LCD level indicator,never again reach for the empty mug,20,49.90
MUG0013,coffee mug with bluetooth-connected coffee grounds scanner for automatized fortune telling,put the smart into coffee reading,20,99.90
OFF3145,pen with pre-warmed ink (tested on the South Pole),the pen is mightier than the cold,50,29.90
COM1001,ambidextrous computer mouse,end the dictate of left and right,10,19.90
COM0404,Easter egg themed webcam for your monitor,put an Easter egg on hardware too,20,149.90
COM0001,Vulcan language vi cheatsheet,learn vi and Vulcan at the same time,3,9.90
COM1536,Klingon language emacs cheatsheet,learn emacs and Klingon at the same time,50,9.90
MOB0555,smartphone case with built-in screen,never miss a message,20,39.90
1 Code Short Description Tagline Quantity Price
2 MUG0007 coffee mug with LCD level indicator never again reach for the empty mug 20 49.90
3 MUG0013 coffee mug with bluetooth-connected coffee grounds scanner for automatized fortune telling put the smart into coffee reading 20 99.90
4 OFF3145 pen with pre-warmed ink (tested on the South Pole) the pen is mightier than the cold 50 29.90
5 COM1001 ambidextrous computer mouse end the dictate of left and right 10 19.90
6 COM0404 Easter egg themed webcam for your monitor put an Easter egg on hardware too 20 149.90
7 COM0001 Vulcan language vi cheatsheet learn vi and Vulcan at the same time 3 9.90
8 COM1536 Klingon language emacs cheatsheet learn emacs and Klingon at the same time 50 9.90
9 MOB0555 smartphone case with built-in screen never miss a message 20 39.90
-63
View File
@@ -1,63 +0,0 @@
import fs from 'node:fs';
import zlib from 'node:zlib';
import color from 'chalk';
const data = fs.readFileSync('data/products.csv', 'utf-8');
const toCamelCase = (str) => {
return str
.trim()
.toLowerCase()
.replace(/[^a-zA-Z0-9]+(.)/g, (match, chr) => chr.toUpperCase());
};
const convertCsvToJson = (products, ar) => {
const resultAr = products.map((str) => {
const fields = str.split(/\s*,\s*/);
const labels = ar.map((label, idx) => {
return [label, isNaN(fields[idx]) ? fields[idx] : Number(fields[idx])];
});
const obj = Object.fromEntries(labels);
// console.log(labels); // Entries Array
//console.log(obj);
return obj;
// return {
// [ar[0]]: fields[0],
// [ar[1]]: fields[1],
// [ar[2]]: fields[2],
// [ar[3]]: Number(fields[3]),
// [ar[4]]: Number(fields[4]),
// };
});
// console.log(resultAr);
const jsonStr = JSON.stringify(resultAr, '', 2);
fs.writeFile('products.json.gz', zlib.gzipSync(jsonStr), 'utf-8', (err) => {
if (err) {
console.log(err);
} else {
console.log(color.green('file created!'));
}
});
};
const productAr = data
.split('\n')
.map((row) => row.replace('\n', ''))
.filter((row) => row !== '');
const headerAr = productAr
.shift()
.split(/\s*,\s*/)
.map(toCamelCase);
// console.log('=======');
// console.log(productAr);
convertCsvToJson(productAr, headerAr);
@@ -1,17 +0,0 @@
{
"name": "u27_zlib",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module",
"dependencies": {
"chalk": "^5.6.2",
"papaparse": "^5.5.4"
}
}
Binary file not shown.
@@ -1,54 +0,0 @@
// const crypto = require('node:crypto');
import crypto from 'node:crypto';
import _ from 'lodash';
const PASSWORD_LENGTH = 10;
const s = '23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ!.,;#$%/+*';
const buf = crypto.randomBytes(PASSWORD_LENGTH);
console.log(buf, Array.from(buf));
const password = Array.from(buf)
.map((byte) => s.charAt(byte % s.length))
.join('');
const getPassword = (amount = 10) => {
const chars = '23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ!.,;#$%/+*'.split('');
return _.shuffle(chars).slice(0, amount).join('');
};
console.log(password);
console.log(getPassword());
// Source - https://stackoverflow.com/a/2450976
// Posted by ChristopheD, modified by community. See post 'Timeline' for change history
// Retrieved 2026-07-10, License - CC BY-SA 4.0
function shuffle(array) {
let currentIndex = array.length;
// While there remain elements to shuffle...
while (currentIndex != 0) {
// Pick a remaining element...
let randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
}
return array;
}
// Used like so
let arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);
// Übung 28: Passwortgenerator
// Was macht der folgende Code?
// OK: Der Titel verrät es schon. Versuche dennoch, das Programm zu verstehen! Benutze die Dokumentation der Standardbibliothek, um nachzuschlagen, was crypto.randomBytes(…) genau macht!
// Bonusfrage: Warum sind in den Zeichen «1», «i» und «l» nicht enthalten, genau so wenig wie «0» und «o»?
@@ -1,21 +0,0 @@
{
"name": "u28_password-generator",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "u28_password-generator",
"version": "1.0.0",
"dependencies": {
"lodash": "^4.18.1"
}
},
"node_modules/lodash": {
"version": "4.18.1",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
"integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
"license": "MIT"
}
}
}
@@ -1,14 +0,0 @@
{
"name": "u28_password-generator",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"type": "module",
"dependencies": {
"lodash": "^4.18.1"
}
}
Binary file not shown.
File diff suppressed because it is too large Load Diff
-21
View File
@@ -1,21 +0,0 @@
// const fs = require('node:fs');
// const zlib = require('node:zlib');
import fs from 'node:fs';
import zlib from 'node:zlib';
const gzipCompressor = zlib.createGzip();
const inputStream = fs.createReadStream('data/products.html');
const outputStream = fs.createWriteStream('data/products.html.gz');
inputStream.on('data', (data) => {
console.log('Pakete (data chunks) werden geladen: ', data.length);
//outputStream.write(zlib.gzipSync(data));
});
inputStream.pipe(gzipCompressor).pipe(outputStream);
// Übung 29: Datenströme
// Schreibe Codebeispiel 239 um, ohne die Funktion pipe(…) zu verwenden!
// TIPP: Um eine Datei päckchenweise lesen- und schreiben zu können, gibt es für das fs Modul die Methoden createReadStream und createWriteStream.
@@ -1,13 +0,0 @@
{
"name": "03_stream",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module"
}
Binary file not shown.
-35
View File
@@ -1,35 +0,0 @@
import os from 'node:os';
import color from 'chalk';
const platform = os.platform();
const cpu = os.cpus().length;
console.log(color.yellow(`I am running on a machine with ${platform} and ${cpu} cores.`));
//console.log(os.cpus()); //gibt ein array aus jeweils cpu kernen
console.log(os.type()); // Darwin
console.log(os.version()); // Darwin mit kernelversion
console.log(os.totalmem()); //RAM in bytes
console.log(os.freemem());
console.log(os.availableParallelism()); // 8 -> ein programm sollte max 8 parallele tasks ausführen?
console.log(os.arch()); // cpu architektur -> arm64
console.log(os.machine()); // arm64
//console.log(os.networkInterfaces());
console.log(os.hostname()); //MacBookAir
console.log(os.release()); // die releasenr und nicht datum
console.log(os.userInfo()); // Object mit Userinfos
console.log(os.userInfo().username);
// Übung 32: Information zum Betriebssystem und der Anzahl der vorhandenen CPUs
// Im Kontext einer Monitoring-Lösung benötigt ein Kunde eine kleine CLI (Command Line Interface)-Anwendung, die es erlaubt, das aktuelle Betriebssystem und die Anzahl der CPUs auf dem jeweiligen Rechner zu ermitteln.
// Vorgehensweise
// 1.Schau dir die Online-Dokumentation zum os-Modul der Standardbibliothek an.
// 2.Erstelle dann ein kurzes Node.js-Programm, das ausgibt, auf welcher Plattform es gerade läuft (also etwa »linux«, »darwin« (OS X) oder »win32«) und wie viele Kerne der Rechner hat.
// Hier eine mögliche Beispielausgabe:
// I am running on a machine with linux and 2 cores.
-27
View File
@@ -1,27 +0,0 @@
{
"name": "u32_os-info",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "u32_os-info",
"version": "1.0.0",
"dependencies": {
"chalk": "^5.6.2"
}
},
"node_modules/chalk": {
"version": "5.6.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz",
"integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==",
"license": "MIT",
"engines": {
"node": "^12.17.0 || ^14.13 || >=16.0.0"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
}
}
}
@@ -1,14 +0,0 @@
{
"name": "u32_os-info",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"type": "module",
"dependencies": {
"chalk": "^5.6.2"
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.