init new course
This commit is contained in:
@@ -1,129 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Object - object</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||
<script src="https://releases.jquery.com/git/jquery-git.slim.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<h1>Objekt - object</h1>
|
||||
<p>
|
||||
Der
|
||||
<a href="https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a>-Typ
|
||||
repräsentiert einen von JavaScript's Datentypen. Er wird verwendet, um verschiedene Schlüsselkollektionen und
|
||||
komplexere Entitäten zu speichern. Objekte können mit dem <strong>Object()</strong>-Konstruktor oder der
|
||||
Objekt-Initialisierer-Syntax erstellt werden.
|
||||
</p>
|
||||
<div class="output alert alert-secondary my-3"></div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const outputEl = document.querySelector('.output');
|
||||
|
||||
const ar = [];
|
||||
const ar2 = new Array(); // oder Array()
|
||||
|
||||
const str = ''; // "" | ``
|
||||
const str2 = new String(); // oder String();
|
||||
|
||||
const zahl = 123;
|
||||
const zahl2 = new Number(); // oder Number();
|
||||
|
||||
const fn = () => {}; // function() {}
|
||||
const fn2 = new Function(); // oder Function();
|
||||
|
||||
const bool = true;
|
||||
const bool2 = new Boolean(); // oder Boolean();
|
||||
|
||||
// =================
|
||||
|
||||
const obj = {};
|
||||
const obj2 = new Object(); // oder Object()
|
||||
|
||||
console.log(typeof str); // 'string' - Objekt vom Typ String
|
||||
console.log(typeof false); // 'boolean' - Objekt vom Typ Boolean
|
||||
console.log(typeof zahl); // 'number' - Objekt vom Typ Number
|
||||
console.log(typeof Infinity); // 'number' - Objekt vom Typ Number
|
||||
console.log(typeof NaN); // 'number' - Objekt vom Typ Number
|
||||
console.log(typeof (() => {})); // 'function' - Objekt vom Typ Function
|
||||
console.log(typeof undefined); // undefined
|
||||
|
||||
console.log(typeof ar); // 'object' vom Typ Array
|
||||
console.log(typeof null); // 'object' vom Typ Null
|
||||
console.log(typeof {}); // 'object' vom Typ Object
|
||||
|
||||
// Eigenschaften können selber definiert werden.
|
||||
|
||||
obj.prop = 'rot';
|
||||
|
||||
console.log(obj.prop); // => 'rot'
|
||||
console.log(obj['prop']); // => 'rot'
|
||||
|
||||
console.log('text'.length); // => 4
|
||||
console.log(['eins', 'zwei', 'drei'].length); // => 3
|
||||
|
||||
const personObj = {
|
||||
firstName: 'John',
|
||||
lastName: 'Wick',
|
||||
age: 45,
|
||||
hobbies: ['Gassi gehen', 'Ballern'],
|
||||
lauf: () => {
|
||||
return 'Person läuft';
|
||||
},
|
||||
schiess: () => {
|
||||
console.log('pew pew');
|
||||
},
|
||||
};
|
||||
|
||||
// Object.freeze(personObj);
|
||||
// personObj.lastname = 'Wock';
|
||||
|
||||
personObj.hairColor = 'Braun';
|
||||
|
||||
console.log(personObj);
|
||||
console.log(personObj.lauf()); // => 'Person läuft'
|
||||
console.log(personObj.schiess());
|
||||
|
||||
console.log(personObj.age); // => 45
|
||||
|
||||
// =============================
|
||||
|
||||
const cssProp = 'border';
|
||||
const color = 'white';
|
||||
|
||||
const cssObj = {
|
||||
'background-color': '#555',
|
||||
'margin-top': '1rem',
|
||||
border: '3px solid tomato',
|
||||
// fontSize, // Uncaught ReferenceError: fontSize is not defined
|
||||
// color: color,
|
||||
color, // Kurzschreibweise seit ES6 - wenn Eigenschaft und Variable gleiche Bezeichnung besitzen
|
||||
};
|
||||
|
||||
console.log(cssObj['background-color']); //=> '#555'
|
||||
console.log(cssObj[cssProp]); //=> '3px solid tomato'
|
||||
|
||||
console.log(cssObj.color); //=> 'white'
|
||||
|
||||
// =========================
|
||||
|
||||
// document.querySelector('h1').style.color = cssObj.color;
|
||||
// document.querySelector('h1').style.backgroundColor = cssObj['background-color'];
|
||||
// document.querySelector('h1').style.padding = '1rem';
|
||||
// document.querySelector('h1').style.border = cssObj['border'];
|
||||
|
||||
$('h1').css({
|
||||
color: 'white',
|
||||
backgroundColor: '#555',
|
||||
padding: '1rem',
|
||||
border: '3px solid tomato',
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,238 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Objekte in JS - Beispiele</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">
|
||||
<h1>Objekte in JS - Beispiele</h1>
|
||||
<div class="output alert alert-secondary my-3"></div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const outputEl = document.querySelector('.output');
|
||||
|
||||
// Beispiel aus openweathermap.org
|
||||
const weatherObj = {
|
||||
coord: {
|
||||
lon: -122.08,
|
||||
lat: 37.39,
|
||||
},
|
||||
weather: [
|
||||
{
|
||||
id: 800,
|
||||
main: 'Clear', // weatherObj.weather[0].main
|
||||
description: 'clear sky',
|
||||
icon: '01d',
|
||||
},
|
||||
{
|
||||
id: 700,
|
||||
main: 'Cloudy',
|
||||
description: 'not clear at all',
|
||||
icon: '02d',
|
||||
},
|
||||
],
|
||||
base: 'stations',
|
||||
main: {
|
||||
temp: 282.55,
|
||||
feels_like: 281.86,
|
||||
temp_min: 280.37,
|
||||
temp_max: 284.26,
|
||||
pressure: 1023,
|
||||
humidity: 100,
|
||||
},
|
||||
visibility: 10000,
|
||||
wind: {
|
||||
speed: 1.5,
|
||||
deg: 350,
|
||||
},
|
||||
clouds: {
|
||||
all: 1,
|
||||
},
|
||||
dt: 1560350645,
|
||||
sys: {
|
||||
type: 1,
|
||||
id: 5122,
|
||||
message: 0.0139,
|
||||
country: 'US',
|
||||
sunrise: 1560343627,
|
||||
sunset: 1560396563,
|
||||
},
|
||||
timezone: -25200,
|
||||
id: 420006353,
|
||||
name: 'Mountain View',
|
||||
cod: 200,
|
||||
};
|
||||
|
||||
outputEl.textContent = weatherObj.name; // => 'Mountain View',
|
||||
outputEl.textContent = weatherObj.weather[1].main; // => 'Cloudy View',
|
||||
|
||||
// Beispiel aus randomuser.me
|
||||
const persons = {
|
||||
results: [
|
||||
{
|
||||
gender: 'female',
|
||||
name: {
|
||||
title: 'Miss',
|
||||
first: 'Krista',
|
||||
last: 'Eich',
|
||||
},
|
||||
location: {
|
||||
street: {
|
||||
number: 2104,
|
||||
name: 'Gartenweg',
|
||||
},
|
||||
city: 'Hohenmölsen',
|
||||
state: 'Mecklenburg-Vorpommern',
|
||||
country: 'Germany',
|
||||
postcode: 76996,
|
||||
coordinates: {
|
||||
latitude: '-50.2839',
|
||||
longitude: '23.5386',
|
||||
},
|
||||
timezone: {
|
||||
offset: '-5:00',
|
||||
description: 'Eastern Time (US & Canada), Bogota, Lima',
|
||||
},
|
||||
},
|
||||
email: 'krista.eich@example.com',
|
||||
login: {
|
||||
uuid: '2443567b-47db-4aa9-8e9e-ba05e3f9fcf3',
|
||||
username: 'organictiger749',
|
||||
password: 'trucking',
|
||||
salt: 'pD1RPPKa',
|
||||
md5: '8a0e13c2df6030ce471c452e51103ad7',
|
||||
sha1: '8f1c4ec24644911fcdb4a4a5c8a2b95509dcdb89',
|
||||
sha256: 'f0a41ee857651c590c0e06091e80d7e3dfa91837b555920aaff7c0e4526e5505',
|
||||
},
|
||||
dob: {
|
||||
date: '1983-06-14T00:47:36.586Z',
|
||||
age: 42,
|
||||
},
|
||||
registered: {
|
||||
date: '2002-04-04T14:49:39.948Z',
|
||||
age: 23,
|
||||
},
|
||||
phone: '0929-5979262',
|
||||
cell: '0178-4888764',
|
||||
id: {
|
||||
name: 'SVNR',
|
||||
value: '53 130683 E 544',
|
||||
},
|
||||
picture: {
|
||||
large: 'https://randomuser.me/api/portraits/women/35.jpg',
|
||||
medium: 'https://randomuser.me/api/portraits/med/women/35.jpg',
|
||||
thumbnail: 'https://randomuser.me/api/portraits/thumb/women/35.jpg',
|
||||
},
|
||||
nat: 'DE',
|
||||
},
|
||||
{
|
||||
gender: 'female',
|
||||
name: {
|
||||
title: 'Miss',
|
||||
first: 'Florence',
|
||||
last: 'Haarhuis',
|
||||
},
|
||||
location: {
|
||||
street: {
|
||||
number: 5383,
|
||||
name: 'Braamhoven',
|
||||
},
|
||||
city: 'Exmorra', // persons.results[1].location.city
|
||||
state: 'Flevoland',
|
||||
country: 'Netherlands',
|
||||
postcode: '8914 YU',
|
||||
coordinates: {
|
||||
latitude: '22.1469',
|
||||
longitude: '-103.2551',
|
||||
},
|
||||
timezone: {
|
||||
offset: '-11:00',
|
||||
description: 'Midway Island, Samoa',
|
||||
},
|
||||
},
|
||||
email: 'florence.haarhuis@example.com',
|
||||
login: {
|
||||
uuid: 'e7ecdba6-817b-4445-8833-217375db7282',
|
||||
username: 'blackduck806',
|
||||
password: 'lback',
|
||||
salt: 'BnCw1UBj',
|
||||
md5: 'e8cd480704a089a0d2fd87186f802461',
|
||||
sha1: 'b0e2e64bb72efd422495bb6f7cea8b86b79f9a9b',
|
||||
sha256: 'b9c4d86027d9269c5a2850d578b753cd8c7662351427bbdb2cec450b1a03adf2',
|
||||
},
|
||||
dob: {
|
||||
date: '1981-06-23T07:46:09.762Z',
|
||||
age: 44,
|
||||
},
|
||||
registered: {
|
||||
date: '2016-10-06T09:20:24.178Z',
|
||||
age: 9,
|
||||
},
|
||||
phone: '(0406) 391733',
|
||||
cell: '(06) 38397250',
|
||||
id: {
|
||||
name: 'BSN',
|
||||
value: '03929007',
|
||||
},
|
||||
picture: {
|
||||
large: 'https://randomuser.me/api/portraits/women/7.jpg',
|
||||
medium: 'https://randomuser.me/api/portraits/med/women/7.jpg',
|
||||
thumbnail: 'https://randomuser.me/api/portraits/thumb/women/7.jpg',
|
||||
},
|
||||
nat: 'NL',
|
||||
},
|
||||
],
|
||||
info: {
|
||||
seed: '1d4ba23c332c6909',
|
||||
results: 2,
|
||||
page: 1,
|
||||
version: '1.4',
|
||||
},
|
||||
};
|
||||
|
||||
outputEl.textContent = persons.results[0].location.coordinates.latitude;
|
||||
outputEl.innerHTML = `<img src="${persons.results[1].picture.large}" />`;
|
||||
|
||||
const contacts = [
|
||||
{
|
||||
firstName: 'Max',
|
||||
lastName: 'Mustermann',
|
||||
phone: ['069 553399', '0171 5522112'],
|
||||
contacts: ['Max', 'Moritz', 'Anne'],
|
||||
},
|
||||
{
|
||||
phone: ['089 6521349', '0152 5552156'],
|
||||
firstName: 'John',
|
||||
lastName: 'Wayne',
|
||||
contacts: ['Darius', 'Berny', 'Boris'],
|
||||
},
|
||||
];
|
||||
|
||||
console.log(contacts[0].contacts[1]); // => 'Moritz'
|
||||
|
||||
const persons2 = [
|
||||
{
|
||||
firstName: 'Max',
|
||||
lastName: 'Mustermann',
|
||||
age: 38,
|
||||
hobbies: ['Tennis', 'Schach'],
|
||||
},
|
||||
{
|
||||
firstName: 'Jane',
|
||||
lastName: 'Doe',
|
||||
age: 24,
|
||||
hobbies: ['Zocken', 'Tanzen'],
|
||||
},
|
||||
];
|
||||
|
||||
console.log(persons2[1].hobbies[1]); // => 'Tanzen'
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,152 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Object - object</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||
<script src="https://releases.jquery.com/git/jquery-git.slim.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<h1>Objekt - object</h1>
|
||||
<p>
|
||||
Der
|
||||
<a href="https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a>-Typ
|
||||
repräsentiert einen von JavaScript's Datentypen. Er wird verwendet, um verschiedene Schlüsselkollektionen und
|
||||
komplexere Entitäten zu speichern. Objekte können mit dem <strong>Object()</strong>-Konstruktor oder der
|
||||
Objekt-Initialisierer-Syntax erstellt werden.
|
||||
</p>
|
||||
<div class="output alert alert-secondary my-3"></div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const outputEl = document.querySelector('.output');
|
||||
|
||||
const ar = [];
|
||||
const ar2 = new Array(); // oder Array()
|
||||
|
||||
const str = ''; // "" | ```
|
||||
const str2 = new String(); // oder String();
|
||||
|
||||
const zahl = 123;
|
||||
const zahl2 = new Number(); // oder Number();
|
||||
|
||||
const fn = () => {}; // function() {}
|
||||
const fn2 = new Function(); // oder Function();
|
||||
|
||||
const bool = true;
|
||||
const bool2 = new Boolean(); // oder Boolean();
|
||||
|
||||
// =================
|
||||
|
||||
const obj = {};
|
||||
const obj2 = new Object(); // oder Object()
|
||||
|
||||
console.log(typeof str); // 'string' - Objekt vom Typ String
|
||||
console.log(typeof false); // 'boolean' - Objekt vom Typ Boolean
|
||||
console.log(typeof zahl); // 'number' - Objekt vom Typ Number
|
||||
console.log(typeof NaN); // 'number' - Objekt vom Typ Number
|
||||
console.log(typeof (() => {})); // 'function' - Objekt vom Typ Function
|
||||
console.log(typeof undefined); // undefined
|
||||
|
||||
console.log(typeof ar); // 'object' vom Typ Array
|
||||
console.log(typeof null); // 'object' vom Typ Null
|
||||
console.log(typeof {}); // 'object' vom Typ Object
|
||||
|
||||
// Eigenschaften können selber definiert werden.
|
||||
|
||||
obj.prop = 'rot';
|
||||
|
||||
console.log(obj.prop); // => 'rot'
|
||||
console.log(obj['prop']); // => 'rot'
|
||||
|
||||
console.log('text'.length); // => 4
|
||||
console.log(['eins', 'zwei', 'drei'].length); // => 3
|
||||
|
||||
const personObj = {
|
||||
firstName: 'John',
|
||||
lastName: 'Wick',
|
||||
age: 45,
|
||||
hobbies: ['Gassi gehen', 'Ballern'],
|
||||
lauf: () => {
|
||||
return 'Person läuft';
|
||||
},
|
||||
// sayHello: function () {
|
||||
// console.log(`${this.firstName} ${this.lastName} says "Hi"`);
|
||||
// },
|
||||
// Kurzschreibweise von "sayHello: function () {"
|
||||
sayHello() {
|
||||
console.log(`${this.firstName} ${this.lastName} says "Hi"`);
|
||||
},
|
||||
|
||||
schiess: () => {
|
||||
console.log('pew pew');
|
||||
},
|
||||
};
|
||||
|
||||
// Object.freeze(personObj);
|
||||
|
||||
personObj.hairColor = 'Braun';
|
||||
|
||||
console.log(personObj);
|
||||
console.log(personObj.lauf()); // => 'Person läuft'
|
||||
console.log(personObj.schiess());
|
||||
console.log(personObj.sayHello());
|
||||
|
||||
console.log(personObj.age); // => 45
|
||||
|
||||
// =============================
|
||||
|
||||
const cssProp = 'border';
|
||||
const color = 'white';
|
||||
|
||||
const cssObj = {
|
||||
'background-color': '#555',
|
||||
'margin-top': '1rem',
|
||||
border: '3px solid tomato',
|
||||
// fontSize, // Uncaught ReferenceError: fontSize is not defined
|
||||
// color: color,
|
||||
color, // Kurzschreibweise seit ES6 - wenn Eigenschaft und Variable gleiche Bezeichnung besitzen
|
||||
};
|
||||
|
||||
console.log(cssObj['background-color']); //=> '#555'
|
||||
console.log(cssObj[cssProp]); //=> '3px solid tomato'
|
||||
|
||||
console.log(cssObj.color); //=> 'white'
|
||||
|
||||
// =========================
|
||||
|
||||
const person = {
|
||||
name: 'Ben',
|
||||
fullName: 'Ben Stiller',
|
||||
introduce() {
|
||||
// 'this' refers to the 'person' object here
|
||||
console.log(`Hello, I am ${this.fullName}.`);
|
||||
},
|
||||
|
||||
// run: () => {
|
||||
// console.log(this); // window - keine neue Referenz
|
||||
// console.log(`${this.fullName} is running!`); // undefined is running
|
||||
// },
|
||||
|
||||
// run: function () {
|
||||
// console.log(this); // person - Object
|
||||
// console.log(`${this.fullName} is running!`); // 'Ben Stiller' is running
|
||||
// },
|
||||
|
||||
run() {
|
||||
// Kurzschreibweise seit ES6 (ECMAScript 2015) von classic function expression (run: function(){})
|
||||
console.log(this); // person - Object
|
||||
console.log(`${this.fullName} is running!`);
|
||||
},
|
||||
};
|
||||
|
||||
person.introduce(); // Output: 'Hello, I am Ben Stiller.'
|
||||
person.run(); // Output: 'Ben Stiller is running!'
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,14 +0,0 @@
|
||||
[
|
||||
{
|
||||
"firstName": "Max",
|
||||
"lastName": "Mustermann",
|
||||
"age": 38,
|
||||
"hobbies": ["Tennis", "Schach"]
|
||||
},
|
||||
{
|
||||
"firstName": "Jane",
|
||||
"lastName": "Doe",
|
||||
"age": 24,
|
||||
"hobbies": ["Zocken", "Tanzen"]
|
||||
}
|
||||
]
|
||||
@@ -1,22 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!--[CDATA[ Kommentar] ]-->
|
||||
<persons>
|
||||
<person>
|
||||
<firstName>Max</firstName>
|
||||
<lastName>Mustermann</lastName>
|
||||
<age>38</age>
|
||||
<hobbies>
|
||||
<hobby>Tennis</hobby>
|
||||
<hobby>Schach</hobby>
|
||||
</hobbies>
|
||||
</person>
|
||||
<person>
|
||||
<firstName>Jane</firstName>
|
||||
<lastName>Doe</lastName>
|
||||
<age>24</age>
|
||||
<hobbies>
|
||||
<hobby>Zocken</hobby>
|
||||
<hobby>Tanzen</hobby>
|
||||
</hobbies>
|
||||
</person>
|
||||
</persons>
|
||||
@@ -1,45 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Object Methoden - keys(), values(), entries()</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">
|
||||
<h1>Object Methoden - keys(), values(), entries()</h1>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const personObj = {
|
||||
firstName: 'John',
|
||||
lastName: 'Wick',
|
||||
age: 45,
|
||||
isAdmin: true,
|
||||
};
|
||||
|
||||
const keys = Object.keys(personObj);
|
||||
console.log(keys); // => ['firstName', 'lastName', 'age', 'isAdmin']
|
||||
|
||||
const values = Object.values(personObj);
|
||||
console.log(values); // => ['John', 'Wick', 45, true]
|
||||
|
||||
const entries = Object.entries(personObj);
|
||||
console.log(entries); // => [['firstName', 'John'], ['lastName','Wick'], ['age',45],['isAdmin', true]]
|
||||
|
||||
// Deklarative Stil
|
||||
entries.forEach((entryAr) => {
|
||||
console.log(`Eigenschaft: ${entryAr[0]}, Wert: ${entryAr[1]}`);
|
||||
});
|
||||
|
||||
// Imperative Stil
|
||||
for (const prop in personObj) {
|
||||
console.log(`Eigenschaft: ${prop}, Wert: ${personObj[prop]}`);
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,73 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>CSV to Obj 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">
|
||||
<h1>CSV to Obj mit destructuring</h1>
|
||||
<div class="output alert alert-secondary my-3"></div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const outputEl = document.querySelector('.output');
|
||||
|
||||
const productsCsv = `name, category, price
|
||||
Klingon Letter Opener, Office Warfare, 19.99
|
||||
Backpack of Holding, Travel, 29.99
|
||||
Tardis Alarmclock, Merchandise, 15.99
|
||||
`;
|
||||
|
||||
// Funktionen
|
||||
const convertCsvToObj = (csv = '') => {
|
||||
const rows = csv.split('\n'); // => ['name, category, price', 'Klingon Letter...']
|
||||
|
||||
const headerRow = rows.shift().split(/\s*,\s*/); // Abgespeichert, falls man es noch benötigt
|
||||
|
||||
console.log(headerRow); // => ['name', 'category', 'price']
|
||||
|
||||
const productRows = rows
|
||||
.map((row) => row.trim()) // "white spaces" des Strings werden entfernt
|
||||
.filter((row) => row !== ''); // leere Einträge werden rausgefiltert
|
||||
|
||||
const ar = productRows.map((row) => {
|
||||
const fields = row.split(/\s*,\s*/); // => ['Klingon Letter Opener', 'Office Warfare', '19.99', ...]
|
||||
|
||||
// const name = fields[0];
|
||||
// const category = fields[1];
|
||||
// const price = fields[2];
|
||||
|
||||
// Destructuring von einem Array
|
||||
const [name, category, price] = fields;
|
||||
|
||||
return {
|
||||
// name: name,
|
||||
// category: category,
|
||||
name,
|
||||
category,
|
||||
price: Number(price),
|
||||
};
|
||||
});
|
||||
|
||||
// console.log(rows);
|
||||
return ar;
|
||||
};
|
||||
|
||||
const products = convertCsvToObj(productsCsv);
|
||||
|
||||
console.log(products);
|
||||
|
||||
outputEl.innerHTML = `<ol>${products
|
||||
.map((product) => {
|
||||
return `<li>Name: ${product.name} Price: <strong>${product.price.toFixed(2)}</strong></li>`;
|
||||
})
|
||||
.join('')}</ol>`;
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,111 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Destructuring von Objekten und Arrays in JS</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">
|
||||
<h1>Destructuring von Objekten und Arrays in JS</h1>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
// Destructuring von Arrays =============
|
||||
const mixedArray = ['Max', 'Mustermann', 33, true, 5, 22, 17, 45, 32, 2];
|
||||
|
||||
// const vorname = mixedArray[0];
|
||||
// const nachname = mixedArray[1];
|
||||
// const alter = mixedArray[2];
|
||||
// const istRaucher = mixedArray[3];
|
||||
// const lottoZahlen = mixedArray.slice(4);
|
||||
|
||||
const [vorname, nachname, alter, istRaucher, ...lottoZahlen] = mixedArray;
|
||||
|
||||
console.log(vorname); // => 'Max'
|
||||
|
||||
// Destructuring von Objekten =============
|
||||
|
||||
const personObj = {
|
||||
firstName: 'John',
|
||||
lastName: 'Wick',
|
||||
age: 52,
|
||||
hobbies: ['Gassi gehen', 'Ballern'],
|
||||
};
|
||||
|
||||
// const firstName = personObj.firstName;
|
||||
// const lastName = personObj.lastName;
|
||||
// const age = personObj.age;
|
||||
// const hobbies = personObj.hobbies;
|
||||
|
||||
// Existierende Eigenschaften können bei der Definition mit ":" direkt umbenannt werden
|
||||
const { firstName, age, lastName, hobbies: sports, isGamer = true } = personObj;
|
||||
|
||||
console.log(firstName); // => 'John'
|
||||
console.log(sports); // => ['Gassi gehen', 'Ballern']
|
||||
console.log(isGamer); // => true
|
||||
console.log(age); // => 52
|
||||
|
||||
// const Slider = (options) => {
|
||||
// if (options.controls) {
|
||||
// const nav = document.querySelector('nav');
|
||||
// nav.classList.add('controls');
|
||||
// }
|
||||
// // code logic
|
||||
// if (options.showDots) {
|
||||
// document.querySelector('.dots').classList.remove('show');
|
||||
// }
|
||||
|
||||
// if (options.mode === 'gallery') {
|
||||
// // ...logic
|
||||
// } else if (options.mode === 'fade') {
|
||||
// // ...logic
|
||||
// } else if (options.mode === 'carousel') {
|
||||
// // ...logic
|
||||
// }
|
||||
// };
|
||||
|
||||
const Slider = (options) => {
|
||||
// Destructuring eines Objektes mit Defaultparametern und Umbenennung
|
||||
const { controls = true, showDots: dots, mode = 'gallery', container: el } = options;
|
||||
|
||||
// logic code wird kürzer durch destructuring
|
||||
const slider = el; // options.container
|
||||
|
||||
if (controls) {
|
||||
const nav = document.querySelector('nav');
|
||||
nav.classList.add('controls');
|
||||
}
|
||||
// code logic
|
||||
if (dots) {
|
||||
document.querySelector('.dots').classList.remove('show');
|
||||
}
|
||||
|
||||
if (mode === 'gallery') {
|
||||
// ...logic
|
||||
} else if (mode === 'fade') {
|
||||
// ...logic
|
||||
} else if (mode === 'carousel') {
|
||||
// ...logic
|
||||
}
|
||||
};
|
||||
|
||||
Slider({
|
||||
container: '.slider',
|
||||
mode: 'gallery', // carousel | fade
|
||||
controls: true,
|
||||
showDots: false,
|
||||
});
|
||||
|
||||
Slider({
|
||||
container: '.slider',
|
||||
|
||||
showDots: false,
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,64 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>JS - Destructuring mit Objekten</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">
|
||||
<h1>JS - Destructuring mit Objekten</h1>
|
||||
<div class="output alert alert-secondary my-3"></div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
// Deklaration
|
||||
const outputEl = document.querySelector('.output');
|
||||
|
||||
const product = {
|
||||
name: 'Klingon Letter Opener',
|
||||
category: 'Office Warfare',
|
||||
price: 19.99,
|
||||
};
|
||||
|
||||
// Funktionen
|
||||
// const formatProduct = (product) => {
|
||||
// return `- ${product.name} - buy now for only $${product.price.toFixed(2)}.`;
|
||||
// };
|
||||
|
||||
// Destructuring eines Objektes
|
||||
const formatProduct = (product) => {
|
||||
const { name, price } = product;
|
||||
|
||||
return `- ${name} - buy now for only $${price.toFixed(2)}.`;
|
||||
};
|
||||
|
||||
// Destructuring eines Objektes in der Parameterliste
|
||||
const formatProduct2 = ({ name, price }) => {
|
||||
return `- ${name} - buy now for only $${price.toFixed(2)}.`;
|
||||
};
|
||||
|
||||
// Destructuring eines Objektes mit Umbennung
|
||||
const formatProduct3 = (product) => {
|
||||
const { name: productName, price: productPrice } = product; // zeigt Umbenennung. Umbennung in längere Bezeichnung ist jedoch unnötig
|
||||
|
||||
return `- ${productName} - buy now for only $${productPrice.toFixed(2)}.`;
|
||||
};
|
||||
|
||||
// Destructuring eines Objektes mit Umbennung und Defaultparameter
|
||||
const formatProduct4 = (product) => {
|
||||
const { name: productName = 'no name', price: productPrice = 0 } = product; // zeigt Umbenennung. Umbennung in längere Bezeichnung ist jedoch unnötig
|
||||
|
||||
return `- ${productName} - buy now for only $${productPrice.toFixed(2)}.`;
|
||||
};
|
||||
|
||||
// Ausgabe
|
||||
console.log(formatProduct2(product));
|
||||
outputEl.textContent = formatProduct4();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,61 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>JS - Destructuring mir Rest-Parameter (...)</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">
|
||||
<h1>JS - Destructuring mir Rest-Parameter (...)</h1>
|
||||
<div class="output alert alert-secondary my-3"></div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const outputEl = document.querySelector('.output');
|
||||
|
||||
const productAr = ['Klingon Letter Opener', 'Office Warfare', '19.99'];
|
||||
const product = {
|
||||
name: 'Klingon Letter Opener',
|
||||
category: 'Office Warfare',
|
||||
price: '19.99',
|
||||
};
|
||||
|
||||
// Destructuring eines Array mit rest-operator
|
||||
const [name, ...everythingElse] = productAr;
|
||||
|
||||
console.log('name: ', name);
|
||||
console.log('everythingElse: ', everythingElse.join(' - '));
|
||||
|
||||
// Destructuring eines Objektes mit rest-operator
|
||||
const { name: productName, ...restObj } = product;
|
||||
|
||||
console.log('productName: ', productName);
|
||||
console.log('restObj', restObj); // => {category: 'Office Warfare', price: '19.99'}
|
||||
|
||||
// Destructuring eines Objektes mit rest-operator
|
||||
const user = {
|
||||
_id: 123,
|
||||
firstName: 'Adel',
|
||||
lastName: 'Jabarkhel',
|
||||
username: 'Megaman',
|
||||
password: 'topsecret',
|
||||
data: [{ avatar: '', profilePic: '' }],
|
||||
};
|
||||
|
||||
console.log(user);
|
||||
|
||||
const { data, password, ...newUser } = user;
|
||||
|
||||
console.log(newUser); // User Object ohne sensbile Daten (password)
|
||||
|
||||
for (const prop in newUser) {
|
||||
outputEl.innerHTML += `${prop} : ${newUser[prop]} <br />`;
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,34 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>JS - Destructuring in der Parameterliste mit Defaultwerten</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">
|
||||
<h1>JS - Destructuring in der Parameterliste mit Defaultwerten</h1>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
// Destructuring in der Parameterliste mit Defaultwert (Object)
|
||||
// { DESTRUCTURING IN PARAMETERLISTE } = { NEUES DEFAULT OBJEKT}
|
||||
const foo = ({ a = 1, b = 2 } = { a: 3, b: 4 }) => `a: ${a}, b: ${b}`;
|
||||
|
||||
const foo2 = (obj = {}) => {
|
||||
const { prop1 = 'wert', prop2 = 'wert2' } = obj;
|
||||
};
|
||||
|
||||
console.log(foo({ a: 7 })); // => 'a: 7, b: 2'
|
||||
console.log(foo({ b: 7 })); // => 'a: 1, b: 7'
|
||||
console.log(foo({ a: 7, b: 8 })); // => 'a: 7, b: 8'
|
||||
|
||||
console.log(foo({})); // => 'a: 1, b: 2'
|
||||
console.log(foo()); // => 'a: 3, b: 4'
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,42 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Rekursion in JS</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">
|
||||
<h1>Rekursion in JS</h1>
|
||||
<div class="output alert alert-secondary my-3"></div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const outputEl = document.querySelector('.output');
|
||||
|
||||
// Funktionen
|
||||
const getProductPrice = () => {
|
||||
const price = Number(prompt('Please insert the product price.'));
|
||||
|
||||
// Basisfall
|
||||
if (isNaN(price) || price < 0) {
|
||||
console.warn('It is not a valid price.');
|
||||
return getProductPrice(); // Rekursion
|
||||
}
|
||||
|
||||
return price;
|
||||
};
|
||||
|
||||
const price = getProductPrice();
|
||||
const text = `Price: $${price.toFixed(2)}`;
|
||||
|
||||
// Ausgabe
|
||||
console.log(text);
|
||||
outputEl.textContent = text;
|
||||
</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>Rekursion - Beispiel Zahl raten</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">
|
||||
<h1>Rekursion - Beispiel Zahl raten</h1>
|
||||
<div class="output alert alert-secondary my-3"></div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const outputEl = document.querySelector('.output');
|
||||
|
||||
const guessNumber = (rndN, round = 1) => {
|
||||
const rndNumber = (!rndN) ? Math.floor(Math.random() * 10) + 1 : rndN; // prettier-ignore
|
||||
console.log(rndNumber);
|
||||
const userGuess = Number(prompt(`Round ${round}:Guess a number between 1 - 10.\nYour guess?`));
|
||||
|
||||
// Basisfall
|
||||
if (userGuess > rndNumber) {
|
||||
alert('Your guess was too high.\nGuess again.');
|
||||
return guessNumber(rndNumber, ++round); // Rekursion
|
||||
} else if (userGuess < rndNumber) {
|
||||
alert('Your guess was too low.\nGuess again.');
|
||||
return guessNumber(rndNumber, ++round); // Rekursion
|
||||
}
|
||||
|
||||
return `Your guess: ${userGuess} is correct in round: ${round}`;
|
||||
};
|
||||
|
||||
outputEl.textContent = guessNumber();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,49 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Rekursion - Beispiel Zahl raten</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">
|
||||
<h1>Rekursion - Beispiel Zahl raten</h1>
|
||||
<div class="output alert alert-secondary my-3"></div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const outputEl = document.querySelector('.output');
|
||||
|
||||
// closure Function
|
||||
const startGuessGame = () => {
|
||||
const rndNumber = Math.floor(Math.random() * 10) + 1; // prettier-ignore
|
||||
let round = 1;
|
||||
|
||||
const guessNumber = () => {
|
||||
console.log(rndNumber);
|
||||
const userGuess = Number(prompt(`Round ${round}:Guess a number between 1 - 10.\nYour guess?`));
|
||||
|
||||
// Basisfall
|
||||
if (userGuess > rndNumber) {
|
||||
alert('Your guess was too high.\nGuess again.');
|
||||
round++;
|
||||
return guessNumber(); // Rekursion
|
||||
} else if (userGuess < rndNumber) {
|
||||
alert('Your guess was too low.\nGuess again.');
|
||||
round++;
|
||||
return guessNumber(); // Rekursion
|
||||
}
|
||||
|
||||
return `Your guess: ${userGuess} is correct in round: ${round}`;
|
||||
};
|
||||
|
||||
return guessNumber();
|
||||
};
|
||||
outputEl.textContent = startGuessGame();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,37 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Rekursion Beispiel: Fakultät errechnen</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">
|
||||
<h1>Rekursion Beispiel: Fakultät errechnen</h1>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const calcFactorial = (n) => {
|
||||
// Base case
|
||||
if (n === 0) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Recursive case
|
||||
return n * calcFactorial(n - 1); // => 3 * (calcFactorial(2) ->) 2 * (calcFactorial(1) ->) 1 * (calcFactorial(0))) 1 )
|
||||
};
|
||||
|
||||
// TODO: mit while Schleife
|
||||
const calcFactorialWithWhile = (n) => {};
|
||||
|
||||
// Test Cases:
|
||||
console.log(calcFactorial(5)); //=> 120;
|
||||
console.log(calcFactorial(3)); //=> 6
|
||||
console.log(calcFactorial(0)); // => 1
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,93 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Rekursion Beispiel: Fibonacci-Reihenfolge errechnen</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">
|
||||
<h1>Rekursion Beispiel: Fibonacci-Reihenfolge errechnen</h1>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const fibonacci = (n) => {
|
||||
// Base cases
|
||||
if (n === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (n === 1) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Recursive case
|
||||
return fibonacci(n - 1) + fibonacci(n - 2);
|
||||
};
|
||||
|
||||
// Test cases
|
||||
console.log(fibonacci(0)); // => 0
|
||||
console.log(fibonacci(1)); // => 1
|
||||
|
||||
console.log(fibonacci(2)); // => 1
|
||||
console.log(fibonacci(3)); // => 2
|
||||
console.log(fibonacci(4)); // => 3
|
||||
console.log(fibonacci(5)); // => 5
|
||||
console.log(fibonacci(6)); // => 8
|
||||
console.log(fibonacci(7)); // => 13
|
||||
console.log(fibonacci(8)); // => 21
|
||||
console.log(fibonacci(10)); // => 55
|
||||
|
||||
// drawLine - mit char
|
||||
|
||||
const drawLine = (width, char = '*') => {
|
||||
// Basisfall
|
||||
if (width === 0) return '';
|
||||
|
||||
return char + drawLine(width - 1, char); // '🤡' + '🤡' + '🤡' + '🤡' + '🤡' + ''
|
||||
};
|
||||
|
||||
console.log(drawLine(5, '🤡')); // => '🤡🤡🤡🤡🤡🤡'
|
||||
console.log(drawLine(20, '🐣')); // => '🐣🐣🐣🐣🐣🐣🐣🐣🐣🐣🐣🐣🐣🐣🐣🐣🐣🐣🐣🐣'
|
||||
|
||||
// =========================
|
||||
const fibonacciMitLog = (n, ebene = 0) => {
|
||||
// Erzeugt Leerzeichen für die visuelle Einrückung in der Konsole
|
||||
const einrückung = ' '.repeat(ebene);
|
||||
|
||||
console.log(`${einrückung}▶️ Rufe fibonacci(${n}) auf`);
|
||||
|
||||
// Base cases
|
||||
if (n === 0) {
|
||||
console.log(`${einrückung}↩️ Base Case: fibonacci(0) gibt 0 zurück`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (n === 1) {
|
||||
console.log(`${einrückung}↩️ Base Case: fibonacci(1) gibt 1 zurück`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Rekursive Aufrufe
|
||||
console.log(`${einrückung}⏳ Berechne links: fibonacci(${n - 1})`);
|
||||
const links = fibonacciMitLog(n - 1, ebene + 1);
|
||||
|
||||
console.log(`${einrückung}⏳ Berechne rechts: fibonacci(${n - 2})`);
|
||||
const rechts = fibonacciMitLog(n - 2, ebene + 1);
|
||||
|
||||
const ergebnis = links + rechts;
|
||||
console.log(`${einrückung}✅ fibonacci(${n}) fertig! ${links} + ${rechts} = ${ergebnis}`);
|
||||
|
||||
return ergebnis;
|
||||
};
|
||||
|
||||
// Testlauf
|
||||
console.log('--- START DER BERECHNUNG ---');
|
||||
fibonacciMitLog(4);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,126 +0,0 @@
|
||||
# Erklärung `fibonacci`-Funktion
|
||||
|
||||
## Wie funktioniert `fibonacci(4)`?
|
||||
|
||||
Bei der Rekursion verzweigt sich die Funktion wie ein Baum, weil in jedem Schritt _zwei_ neue Aufrufe gestartet werden: `fibonacci(n - 1)` und `fibonacci(n - 2)`. JavaScript arbeitet diesen Baum von **oben nach unten** und von **links nach rechts** ab.
|
||||
|
||||
### Der Ablauf Schritt für Schritt
|
||||
|
||||
Hier ist die exakte Reihenfolge, wie JavaScript die Funktionen aufruft und auflöst:
|
||||
|
||||
1. **`fibonacci(4)`** wird aufgerufen.
|
||||
|
||||
- Da $n > 1$, will die Funktion `fibonacci(3) + fibonacci(2)` rechnen. Sie muss aber **zuerst** den linken Teil (`fibonacci(3)`) komplett berechnen.
|
||||
|
||||
2. **`fibonacci(3)`** wird aufgerufen.
|
||||
|
||||
- Will `fibonacci(2) + fibonacci(1)` rechnen. Wartet auf den linken Teil (`fibonacci(2)`).
|
||||
|
||||
3. **`fibonacci(2)`** wird aufgerufen.
|
||||
|
||||
- Will `fibonacci(1) + fibonacci(0)` rechnen. Wartet auf links (`fibonacci(1)`).
|
||||
|
||||
4. **`fibonacci(1)`** wird aufgerufen.
|
||||
|
||||
- **Base Case greift!** Gibt **`1`** zurück.
|
||||
|
||||
5. Zurück bei `fibonacci(2)`: Der linke Teil ist bereit (`1`). Jetzt wird der rechte Teil (`fibonacci(0)`) aufgerufen.
|
||||
6. **`fibonacci(0)`** wird aufgerufen.
|
||||
|
||||
- **Base Case greift!** Gibt **`0`** zurück.
|
||||
|
||||
7. **`fibonacci(2)` wird aufgelöst:** Rechnet `1 + 0` und gibt **`1`** zurück an `fibonacci(3)`.
|
||||
8. Zurück bei `fibonacci(3)`: Der linke Teil ist bereit (`1`). Jetzt wird der rechte Teil (`fibonacci(1)`) aufgerufen.
|
||||
9. **`fibonacci(1)`** wird aufgerufen.
|
||||
|
||||
- **Base Case greift!** Gibt **`1`** zurück.
|
||||
|
||||
10. **`fibonacci(3)` wird aufgelöst:** Rechnet `1 + 1` (Ergebnis aus Schritt 7 + Schritt 9) und gibt **`2`** zurück an `fibonacci(4)`.
|
||||
11. Zurück bei `fibonacci(4)`: Der linke Teil (`fibonacci(3)`) ist endlich fertig und hat den Wert `2`. Jetzt wird der komplette rechte Ast (**`fibonacci(2)`**) berechnet.
|
||||
12. **`fibonacci(2)`** wird aufgerufen (für die rechte Seite von `fibonacci(4)`).
|
||||
|
||||
- Ruft intern wieder `fibonacci(1)` (gibt `1`) und `fibonacci(0)` (gibt `0`) auf.
|
||||
- Rechnet `1 + 0` und gibt **`1`** zurück.
|
||||
|
||||
13. **`fibonacci(4)` wird final aufgelöst:** \* Rechnet das Ergebnis von links (`2`) + das Ergebnis von rechts (`1`).
|
||||
|
||||
- **Endergebnis: `3**`.
|
||||
|
||||
---
|
||||
|
||||
## Die Schritte mit `console.log` sichtbar machen
|
||||
|
||||
Ja, das kann man wunderbar mit `console.log` sichtbar machen! Am besten fügt man eine Einrückung (`indent`) hinzu, die sich mit jeder Ebene vertieft. So sieht man direkt die "Baumstruktur" in der Konsole.
|
||||
|
||||
Hier ist der modifizierte Code:
|
||||
|
||||
```javascript
|
||||
const fibonacciMitLog = (n, ebene = 0) => {
|
||||
// Erzeugt Leerzeichen für die visuelle Einrückung in der Konsole
|
||||
const einrückung = ' '.repeat(ebene);
|
||||
|
||||
console.log(`${einrückung}▶️ Rufe fibonacci(${n}) auf`);
|
||||
|
||||
// Base cases
|
||||
if (n === 0) {
|
||||
console.log(`${einrückung}↩️ Base Case: fibonacci(0) gibt 0 zurück`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (n === 1) {
|
||||
console.log(`${einrückung}↩️ Base Case: fibonacci(1) gibt 1 zurück`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Rekursive Aufrufe
|
||||
console.log(`${einrückung}⏳ Berechne links: fibonacci(${n - 1})`);
|
||||
const links = fibonacciMitLog(n - 1, ebene + 1);
|
||||
|
||||
console.log(`${einrückung}⏳ Berechne rechts: fibonacci(${n - 2})`);
|
||||
const rechts = fibonacciMitLog(n - 2, ebene + 1);
|
||||
|
||||
const ergebnis = links + rechts;
|
||||
console.log(`${einrückung}✅ fibonacci(${n}) fertig! ${links} + ${rechts} = ${ergebnis}`);
|
||||
|
||||
return ergebnis;
|
||||
};
|
||||
|
||||
// Testlauf
|
||||
console.log('--- START DER BERECHNUNG ---');
|
||||
fibonacciMitLog(4);
|
||||
```
|
||||
|
||||
### Das Ergebnis in der Konsole:
|
||||
|
||||
Wenn du diesen Code ausführst, siehst du exakt, wie JavaScript durch die Ebenen wandert:
|
||||
|
||||
```text
|
||||
--- START DER BERECHNUNG ---
|
||||
▶️ Rufe fibonacci(4) auf
|
||||
⏳ Berechne links: fibonacci(3)
|
||||
▶️ Rufe fibonacci(3) auf
|
||||
⏳ Berechne links: fibonacci(2)
|
||||
▶️ Rufe fibonacci(2) auf
|
||||
⏳ Berechne links: fibonacci(1)
|
||||
▶️ Rufe fibonacci(1) auf
|
||||
↩️ Base Case: fibonacci(1) gibt 1 zurück
|
||||
⏳ Berechne rechts: fibonacci(0)
|
||||
▶️ Rufe fibonacci(0) auf
|
||||
↩️ Base Case: fibonacci(0) gibt 0 zurück
|
||||
✅ fibonacci(2) fertig! 1 + 0 = 1
|
||||
⏳ Berechne rechts: fibonacci(1)
|
||||
▶️ Rufe fibonacci(1) auf
|
||||
↩️ Base Case: fibonacci(1) gibt 1 zurück
|
||||
✅ fibonacci(3) fertig! 1 + 1 = 2
|
||||
⏳ Berechne rechts: fibonacci(2)
|
||||
▶️ Rufe fibonacci(2) auf
|
||||
⏳ Berechne links: fibonacci(1)
|
||||
▶️ Rufe fibonacci(1) auf
|
||||
↩️ Base Case: fibonacci(1) gibt 1 zurück
|
||||
⏳ Berechne rechts: fibonacci(0)
|
||||
▶️ Rufe fibonacci(0) auf
|
||||
↩️ Base Case: fibonacci(0) gibt 0 zurück
|
||||
✅ fibonacci(2) fertig! 1 + 0 = 1
|
||||
✅ fibonacci(4) fertig! 2 + 1 = 3
|
||||
|
||||
```
|
||||
@@ -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>Rekursion Beispiel: Summe eine Arrays errechnen</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">
|
||||
<h1>Rekursion Beispiel: Summe eine Arrays errechnen</h1>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const sumArray = (arr) => {
|
||||
// Base case: when the array is empty, return 0
|
||||
if (arr.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
// Recursive case: add the first element to the sum of the rest of the array
|
||||
return arr[0] + sumArray(arr.slice(1)); // => 1 + [2, 3, 4, 5] -> 2 + [3, 4, 5] -> 3 + [4, 5] -> 4 + [5] -> 5 + [] -> 0
|
||||
};
|
||||
|
||||
const sumArrayReduce = (arr) => {
|
||||
return arr.reduce((a, b) => a + b, 0);
|
||||
};
|
||||
|
||||
const sumArrayWhile = (arr) => {
|
||||
let i = arr.length;
|
||||
let sum = 0;
|
||||
if (i === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
while (--i > -1) {
|
||||
sum += arr[i];
|
||||
}
|
||||
return sum;
|
||||
};
|
||||
// Test cases
|
||||
console.time('rekursion');
|
||||
console.log(sumArray([1, 2, 3, 4, 5])); // => 15
|
||||
console.timeEnd('rekursion');
|
||||
|
||||
// Test cases
|
||||
console.time('reduce');
|
||||
console.log(sumArrayReduce([1, 2, 3, 4, 5])); // => 15
|
||||
console.timeEnd('reduce');
|
||||
|
||||
// Test cases
|
||||
console.time('while');
|
||||
console.log(sumArrayWhile([1, 2, 3, 4, 5])); // => 15
|
||||
console.timeEnd('while');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,4 +0,0 @@
|
||||
name, category, price
|
||||
Klingon Letter Opener, Office Warfare, 19.99
|
||||
Backpack of Holding, Travel, 29.99
|
||||
Tardis Alarmclock, Merchandise, 15.99
|
||||
|
@@ -1,100 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>The Pyramid Of The Doom - callback hell - Beispiele</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
|
||||
<style>
|
||||
.box {
|
||||
border-radius: 1rem;
|
||||
background-color: tomato;
|
||||
border: 5px solid #333;
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
padding: 1rem;
|
||||
color: white;
|
||||
margin: 1rem;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<h1>The Pyramid Of The Doom - callback hell - Beispiele</h1>
|
||||
|
||||
<!-- .boxes>.box.box-$*4>span{$} -->
|
||||
|
||||
<div class="boxes">
|
||||
<div class="box box-1"><span>1</span></div>
|
||||
<div class="box box-2"><span>2</span></div>
|
||||
<div class="box box-3"><span>3</span></div>
|
||||
<div class="box box-4"><span>4</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
// $('.box-1').animate({ marginLeft: '300px' }, 800, () => {
|
||||
// $('.box-2').animate({ marginLeft: '300px' }, 800, () => {
|
||||
// $('.box-3').animate({ marginLeft: '300px' }, 800, () => {
|
||||
// $('.box-4').animate({ marginLeft: '300px' }, 800, () => {
|
||||
// $('.boxes').fadeOut(800, () => {
|
||||
// console.log('Animation fertig');
|
||||
// });
|
||||
// });
|
||||
// });
|
||||
// });
|
||||
// });
|
||||
|
||||
$('.box-1').animate({ marginLeft: '300px' }, 800, () => {});
|
||||
$('.box-2')
|
||||
.delay(800)
|
||||
.animate({ marginLeft: '300px' }, 800, () => {});
|
||||
$('.box-3')
|
||||
.delay(1600)
|
||||
.animate({ marginLeft: '300px' }, 800, () => {});
|
||||
$('.box-4')
|
||||
.delay(2400)
|
||||
.animate({ marginLeft: '300px' }, 800, () => {});
|
||||
$('.boxes')
|
||||
.delay(3200)
|
||||
.fadeOut(800, () => {});
|
||||
|
||||
// the pyramid of doom appears
|
||||
|
||||
setTimeout(() => {
|
||||
console.log('wird verzögert ausgeführt');
|
||||
}, 10000); // 10000ms
|
||||
|
||||
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);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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>Promise Object - Syntax</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">
|
||||
<h1>Promise Objekt - Syntaxaufbau</h1>
|
||||
<p>
|
||||
Das
|
||||
<a href="https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a>
|
||||
Objekt stellt eine Repräsentation einer eventuellen Ausführung (oder eines Fehlschlags) einer
|
||||
<strong>asynchronen</strong>
|
||||
Operation und den daraus resultierenden Ergebnissen dar.
|
||||
</p>
|
||||
<img
|
||||
src="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/promises.png"
|
||||
alt=""
|
||||
class="img-thumbnail" />
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
// async operation (hier simuliert)
|
||||
const ergebnis = 21 * 2;
|
||||
if (ergebnis !== 42) {
|
||||
// console.log(`Error: ${ergebnis} is NOT correct`);
|
||||
reject(`Error: ${ergebnis} is NOT correct`);
|
||||
}
|
||||
|
||||
// console.log(`${ergebnis} is correct`);
|
||||
resolve(ergebnis);
|
||||
});
|
||||
|
||||
promise.then(
|
||||
(result) => {
|
||||
console.log('OK: ', result);
|
||||
},
|
||||
(error) => {
|
||||
console.log('KO: ', error);
|
||||
},
|
||||
);
|
||||
|
||||
// Empfohlene Schreibweise - then nur für "Erfolg" (resolve) - catch für "Fehler" (reject)
|
||||
promise
|
||||
.then((result) => {
|
||||
console.log('OK: ', result);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log('KO: ', error);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,26 +0,0 @@
|
||||
const fs = require('fs'); // Modul aus der Standardlibrary von node
|
||||
|
||||
const getFile = (path = '') => {
|
||||
return new Promise((resolve, reject) => {
|
||||
//asynchrones auslesen einer Datei
|
||||
fs.readFile(path, 'utf-8', (error, data) => {
|
||||
if (error) {
|
||||
// console.error(error);
|
||||
reject(error);
|
||||
}
|
||||
// console.log(data);
|
||||
resolve(data);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
console.log('weiter im code');
|
||||
|
||||
// Funktionsaufruf einer Funktion, die asynchrone Prozesse
|
||||
getFile('02_promise-aufbau.html')
|
||||
.then((data) => {
|
||||
console.log(data);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
});
|
||||
@@ -1,2 +0,0 @@
|
||||
// console ist aus dem Node core (Standard-library)
|
||||
console.log('Hello JS from system (node)');
|
||||
@@ -1,36 +0,0 @@
|
||||
.header-main {
|
||||
width: 100%;
|
||||
height: 400px;
|
||||
background-color: #222;
|
||||
color: white;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
.header-main .content-box figure figcaption {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.menu-main {
|
||||
background-color: tomato;
|
||||
}
|
||||
.menu-main ul {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
}
|
||||
.menu-main ul li {
|
||||
border-right: 1px solid #333;
|
||||
}
|
||||
.menu-main ul li:last-child {
|
||||
border-right: none;
|
||||
}
|
||||
.menu-main ul li a {
|
||||
text-decoration: none;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 1px;
|
||||
color: white;
|
||||
display: inline-block;
|
||||
padding: 0.5rem 1rem;
|
||||
}
|
||||
|
||||
/*# sourceMappingURL=main.css.map */
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sourceRoot":"","sources":["../scss/main.scss"],"names":[],"mappings":"AAGA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;;AAII;EACE;;;AAOR;EACE;;AACA;EACE;EACA;;AACA;EACE;;AACA;EACE;;AAEF;EACE;EACA;EACA;EACA;EACA;EACA","file":"main.css"}
|
||||
@@ -1,19 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
(() => {
|
||||
// === DOM & VARS =======
|
||||
const DOM = {};
|
||||
|
||||
// === INIT =============
|
||||
const init = () => {
|
||||
console.log('init...');
|
||||
};
|
||||
|
||||
// === EVENTHANDLER =====
|
||||
|
||||
// === XHR/FETCH ========
|
||||
|
||||
// === FUNCTIONS ========
|
||||
|
||||
init();
|
||||
})();
|
||||
@@ -1,43 +0,0 @@
|
||||
// sass assets/scss/main.scss:assets/css/main.css
|
||||
|
||||
// Header Bereich
|
||||
.header-main {
|
||||
width: 100%;
|
||||
height: 400px;
|
||||
background-color: #222;
|
||||
color: white;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
|
||||
.content-box {
|
||||
figure {
|
||||
figcaption {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Menu Main
|
||||
.menu-main {
|
||||
background-color: tomato;
|
||||
ul {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
li {
|
||||
border-right: 1px solid #333;
|
||||
&:last-child {
|
||||
border-right: none;
|
||||
}
|
||||
a {
|
||||
text-decoration: none;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 1px;
|
||||
color: white;
|
||||
display: inline-block;
|
||||
padding: 0.5rem 1rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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>Webseite mit Sass</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||
<link rel="stylesheet" href="assets/css/main.css" />
|
||||
<script src="assets/js/main.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<header class="header-main">
|
||||
<div class="content-box">
|
||||
<figure>
|
||||
<img src="https://dummyimage.com/160x100" alt="Logo" />
|
||||
<figcaption>Webseite mit Sass</figcaption>
|
||||
</figure>
|
||||
</div>
|
||||
</header>
|
||||
<!-- nav.menu-main>ul.list>li*4>a[href="#"]{Link $} -->
|
||||
<nav class="menu-main">
|
||||
<ul class="list">
|
||||
<li><a href="#">Home</a></li>
|
||||
<li><a href="#">About</a></li>
|
||||
<li><a href="#">Projects</a></li>
|
||||
<li><a href="#">Contact</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<h1>Webseite mit Sass</h1>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,4 +0,0 @@
|
||||
name, category, price
|
||||
Klingon Letter Opener, Office Warfare, 19.99
|
||||
Backpack of Holding, Travel, 29.99
|
||||
Tardis Alarmclock, Merchandise, 15.99
|
||||
|
@@ -1,31 +0,0 @@
|
||||
// fs = FileSystem Modul aus der Node Standardbib
|
||||
// const fs = require('fs'); // commonjs - Node Schreibweise
|
||||
// const chalk = require('chalk');
|
||||
import fs from 'fs'; // module - ESM Schreibweise
|
||||
import chalk from 'chalk';
|
||||
|
||||
// Funktion mir einem asynchronen Prozess
|
||||
const getContentBy = (path) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
// asynchroner Prozess
|
||||
fs.readFile(path, 'utf-8', (err, data) => {
|
||||
if (err) {
|
||||
// console.error(err);
|
||||
reject(err);
|
||||
}
|
||||
// console.log(data);
|
||||
resolve(data);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Funktionsaufruf einer Funktion mit asynchronen Prozess
|
||||
getContentBy('data/products.csv')
|
||||
.then((data) => {
|
||||
console.log(chalk.yellow(data));
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(chalk.red(err));
|
||||
});
|
||||
|
||||
console.log('weiter im code...');
|
||||
@@ -1,28 +0,0 @@
|
||||
{
|
||||
"name": "01_promise-and-readfile",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "01_promise-and-readfile",
|
||||
"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": "01_promise-and-readfile",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"license": "ISC",
|
||||
"author": "",
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"dependencies": {
|
||||
"chalk": "^5.6.2"
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
// commonjs - Schreibweise mit "require"
|
||||
const fs = require('node:fs'); // "fs" ist ein Modul aus der Node Standardbib und kann mit Prefix "node:" hervorgehoben werden
|
||||
const chalk = require('chalk');
|
||||
|
||||
const getFileBy = (path, encoding = 'utf-8') => {
|
||||
return new Promise((resolve, reject) => {
|
||||
// async process
|
||||
fs.readFile(path, encoding, (err, data) => {
|
||||
if (err) {
|
||||
// console.error(err);
|
||||
reject(err);
|
||||
}
|
||||
|
||||
// console.log(data);
|
||||
resolve(data);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Funktionsaufruf von Funktion mit async process
|
||||
getFileBy('package.json')
|
||||
.then((data) => {
|
||||
console.log(chalk.yellow(data));
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(chalk.red(err));
|
||||
});
|
||||
@@ -1,86 +0,0 @@
|
||||
{
|
||||
"name": "commonjs",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "commonjs",
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"chalk": "^4.1.2"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-styles": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
|
||||
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-convert": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/chalk": {
|
||||
"version": "4.1.2",
|
||||
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
|
||||
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-styles": "^4.1.0",
|
||||
"supports-color": "^7.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/chalk?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/color-convert": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
||||
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-name": "~1.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/color-name": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
|
||||
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/has-flag": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
|
||||
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/supports-color": {
|
||||
"version": "7.2.0",
|
||||
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
|
||||
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"has-flag": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"name": "commonjs",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"type": "commonjs",
|
||||
"dependencies": {
|
||||
"chalk": "^4.1.2"
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
// esm - Schreibweise mit "import"
|
||||
import fs from 'node:fs'; // "fs" ist ein Modul aus der Node Standardbib und kann mit Prefix "node:" hervorgehoben werden
|
||||
import chalk from 'chalk';
|
||||
|
||||
const getFileBy = (path, encoding = 'utf-8') => {
|
||||
return new Promise((resolve, reject) => {
|
||||
// async process
|
||||
fs.readFile(path, encoding, (err, data) => {
|
||||
if (err) {
|
||||
// console.error(err);
|
||||
reject(err);
|
||||
}
|
||||
|
||||
// console.log(data);
|
||||
resolve(data);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Funktionsaufruf von Funktion mit async process
|
||||
getFileBy('package.json')
|
||||
.then((data) => {
|
||||
console.log(chalk.yellow(data));
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(chalk.red(err));
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
{
|
||||
"name": "module",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "module",
|
||||
"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": "module",
|
||||
"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,40 +0,0 @@
|
||||
// esm - Schreibweise mit "import"
|
||||
import fs from 'node:fs'; // "fs" ist ein Modul aus der Node Standardbib und kann mit Prefix "node:" hervorgehoben werden
|
||||
import color from 'chalk';
|
||||
|
||||
const getFileBy = (path, encoding = 'utf-8') => {
|
||||
return new Promise((resolve, reject) => {
|
||||
// async process
|
||||
fs.readFile(path, encoding, (err, data) => {
|
||||
if (err) {
|
||||
// console.error(err);
|
||||
reject(err);
|
||||
}
|
||||
|
||||
// console.log(data);
|
||||
resolve(data);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const getPromisesFileBy = (path, encoding = 'utf-8') => {
|
||||
// Unterobjekt "promises" von fs besitzt Ummantelung von Promise-Objekt und Verarbeitung der Callback-Funktion
|
||||
return fs.promises.readFile(path, encoding);
|
||||
};
|
||||
|
||||
// Funktionsaufruf von Funktion mit async process
|
||||
getFileBy('package.json')
|
||||
.then((data) => {
|
||||
console.log(color.yellow(data));
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(color.red(err));
|
||||
});
|
||||
|
||||
getPromisesFileBy('package.json')
|
||||
.then((data) => {
|
||||
console.log(color.green(data));
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(color.magenta(err));
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
{
|
||||
"name": "module",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "module",
|
||||
"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": "03_fs-promises",
|
||||
"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,35 +0,0 @@
|
||||
// esm - Schreibweise mit "import"
|
||||
import fs from 'node:fs'; // "fs" ist ein Modul aus der Node Standardbib und kann mit Prefix "node:" hervorgehoben werden
|
||||
import color from 'chalk';
|
||||
|
||||
// async ... await
|
||||
const getFileBy = async (path, encoding = 'utf-8') => {
|
||||
try {
|
||||
const result = await fs.promises.readFile(path, encoding);
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const getPromiseFileBy = (path, encoding = 'utf-8') => {
|
||||
return new Promise((resolve, reject) => {
|
||||
fs.readFile(path, encoding, (err, data) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
resolve(data);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
getFileBy('package.json')
|
||||
.then((data) => {
|
||||
console.log(color.green(data));
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(color.magenta(err));
|
||||
})
|
||||
.finally(() => {
|
||||
console.log(color.yellow('process finished'));
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
{
|
||||
"name": "module",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "module",
|
||||
"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": "04_async-await",
|
||||
"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 +0,0 @@
|
||||
Ich bin file01
|
||||
@@ -1 +0,0 @@
|
||||
Ich bin file02
|
||||
@@ -1 +0,0 @@
|
||||
Ich bin file03
|
||||
@@ -1 +0,0 @@
|
||||
Ich bin file04
|
||||
@@ -1,28 +0,0 @@
|
||||
import fs from 'node:fs';
|
||||
import color from 'chalk';
|
||||
|
||||
const getFileBy = (path, encoding = 'utf-8') => {
|
||||
return fs.promises.readFile(path, encoding);
|
||||
};
|
||||
|
||||
// getFileBy('data/file01.txt')
|
||||
// .then((data) => {
|
||||
// console.log(color.green(data));
|
||||
// })
|
||||
// .catch((err) => {
|
||||
// console.log(color.red(err));
|
||||
// });
|
||||
|
||||
Promise.all([
|
||||
getFileBy('data/file01.txt'),
|
||||
getFileBy('data/file02.txt'),
|
||||
// getFileBy('data/404'),
|
||||
getFileBy('data/file03.txt'),
|
||||
getFileBy('data/file04.txt'),
|
||||
])
|
||||
.then((data) => {
|
||||
console.log(data);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(err);
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
{
|
||||
"name": "05_promise-all",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "05_promise-all",
|
||||
"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": "05_promise-all",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"keywords": [],
|
||||
"license": "ISC",
|
||||
"author": "",
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"chalk": "^5.6.2"
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
Ich bin eine Datei!
|
||||
@@ -1,16 +0,0 @@
|
||||
// const fs = require('fs');
|
||||
// const util = require('util');
|
||||
import fs from 'node:fs';
|
||||
import util from 'node:util';
|
||||
|
||||
// util.promisify fängt das letzte Argument als Callback-Funktion ab und ummantel die Funktion mit einem Promise-Objekt.
|
||||
// Das ummantelte Promise-Objekt wird zusätzlich von einer weiteren Funktion mit den Argumenten ummantelt.
|
||||
|
||||
// https://javascript.info/promisify
|
||||
// https://medium.com/trabe/understanding-nodes-promisify-and-callbackify-d2b04efde0e0
|
||||
|
||||
const getFileContent = util.promisify(fs.readFile);
|
||||
|
||||
getFileContent('data/file.txt', 'utf8')
|
||||
.then((data) => console.log(data))
|
||||
.catch((err) => console.error(`Something went wrong: ${err}`));
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"name": "01_util-promisify",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"type": "module"
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Switch Case</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">
|
||||
<h1>Switch Case</h1>
|
||||
<p>
|
||||
Die
|
||||
<a href="https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/switch">switch</a
|
||||
>-Anweisung wertet einen Ausdruck aus, vergleicht den Wert des Ausdrucks mit einer Reihe von
|
||||
<strong>case</strong>-Klauseln und führt Anweisungen nach der ersten <strong>case</strong>-Klausel mit
|
||||
passendem Wert aus, bis eine <strong>break</strong>-Anweisung erreicht wird. Die default-Klausel einer
|
||||
switch-Anweisung wird angesprungen, wenn keine <strong>case</strong>-Klausel den Wert des Ausdrucks trifft.
|
||||
</p>
|
||||
<div class="output alert alert-secondary my-3"></div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const outputEl = document.querySelector('.output');
|
||||
|
||||
let taxRate;
|
||||
|
||||
const category = 'books'; //prompt('What is the product category?').trim().toLowerCase();
|
||||
|
||||
const productPrice = 100;
|
||||
|
||||
// if (category === 'books') {
|
||||
// taxRate = 1.07;
|
||||
// } else if (category === 'vehicle') {
|
||||
// taxRate = 1.19;
|
||||
// } else if (category === 'fruits') {
|
||||
// taxRate = 1.05;
|
||||
// }
|
||||
|
||||
switch (category) {
|
||||
case 'books':
|
||||
taxRate = 1.07;
|
||||
break;
|
||||
case 'vehicle':
|
||||
taxRate = 1.19;
|
||||
break;
|
||||
|
||||
case 'software':
|
||||
case 'fruits':
|
||||
taxRate = 1.05;
|
||||
break;
|
||||
|
||||
default:
|
||||
console.warn('category not found');
|
||||
taxRate = 1.19;
|
||||
}
|
||||
|
||||
// ======
|
||||
|
||||
const getColorByName = (variant = '') => {
|
||||
let color;
|
||||
switch (variant.trim().toLowerCase()) {
|
||||
case 'primary':
|
||||
color = '#0d6efd';
|
||||
break;
|
||||
case 'secondary':
|
||||
color = '#6c757d';
|
||||
break;
|
||||
case 'warning':
|
||||
color = '#ffc720';
|
||||
break;
|
||||
case 'success':
|
||||
color = '#13653f';
|
||||
break;
|
||||
case 'info':
|
||||
color = '#25cff2';
|
||||
break;
|
||||
case 'error':
|
||||
case 'danger':
|
||||
color = '#a52834';
|
||||
break;
|
||||
case 'light':
|
||||
color = '#babbbc';
|
||||
break;
|
||||
case 'dark':
|
||||
color = '#373b3e';
|
||||
break;
|
||||
|
||||
default:
|
||||
console.warn('variant not found');
|
||||
color: 'white';
|
||||
}
|
||||
return color;
|
||||
};
|
||||
|
||||
document.querySelector('h1').style.backgroundColor = getColorByName('warning');
|
||||
|
||||
const totalPrice = productPrice * taxRate;
|
||||
outputEl.textContent = `Total price: $${totalPrice.toFixed(2)}`;
|
||||
console.log('weiter im code...');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1 +0,0 @@
|
||||
# Exkurs: Webseite mit Sass und package.json (scripts)
|
||||
@@ -1,6 +0,0 @@
|
||||
# Meeting Fr. 03.07.2026
|
||||
|
||||
- [x] 15:35 - 15:45 Uhr Kahleel
|
||||
- [x] 15:45 - 15:55 Uhr Adel
|
||||
- [x] 15:55 - 16:05 Uhr Andreas
|
||||
- [x] 16:05 - 15:15 Uhr Ersin
|
||||
@@ -1 +0,0 @@
|
||||
# Exkurs: Webseite mit Sass und package.json (scripts) Part II
|
||||
@@ -1,188 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Mehrdimensionales 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">
|
||||
<h1>Mehrdimensionales Array</h1>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const gradesTable = [
|
||||
['Name', 'Mathematics', 'English', 'Biology'],
|
||||
['Anna', 85, 92, 78],
|
||||
['Ben', 90, 88, 84],
|
||||
['Clara', 76, 95, 89],
|
||||
];
|
||||
|
||||
console.log(gradesTable[3][2]); // => 95
|
||||
console.log(['Clara', 76, 95, 89][2]); // => 95
|
||||
console.log(gradesTable[1][3]); // => 78
|
||||
|
||||
// Access to Anna's math grade
|
||||
const annasMathGrade = gradesTable[1][1]; // => 85
|
||||
|
||||
// Access to Clara's biology grade
|
||||
const clarasBioGrade = gradesTable[3][3]; // => 89
|
||||
|
||||
// Change Anna's math grade to 88
|
||||
gradesTable[1][1] = 88;
|
||||
gradesTable[1].splice(1, 1, 88);
|
||||
|
||||
// Add a new row for another student
|
||||
gradesTable.push(['David', 82, 79, 91]);
|
||||
|
||||
// TODO: optionale Übung: gradeTable in gradesObject über eigene Funktion parseToObj() umwandeln. Tipp: map. Beispiel 01_csv-to-obj.html aus Tag 12
|
||||
|
||||
const gradesTableObj = [
|
||||
{
|
||||
name: 'Anna',
|
||||
scores: [
|
||||
{
|
||||
name: 'Mathematics',
|
||||
score: 85,
|
||||
},
|
||||
{
|
||||
name: 'English',
|
||||
score: 92,
|
||||
},
|
||||
{
|
||||
name: 'Biology',
|
||||
score: 78,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Ben',
|
||||
scores: [
|
||||
{
|
||||
name: 'Mathematics',
|
||||
score: 76,
|
||||
},
|
||||
{
|
||||
name: 'English',
|
||||
score: 95,
|
||||
},
|
||||
{
|
||||
name: 'Biology',
|
||||
score: 89,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Clara',
|
||||
scores: [
|
||||
{
|
||||
name: 'Mathematics',
|
||||
score: 85,
|
||||
},
|
||||
{
|
||||
name: 'English',
|
||||
score: 92,
|
||||
},
|
||||
{
|
||||
name: 'Biology',
|
||||
score: 78,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
// ===============
|
||||
|
||||
const shoppingList = [
|
||||
['Fruits', 'Apples', 'Bananas', 'Oranges'],
|
||||
['Vegetables', 'Carrots', 'Broccoli', 'Spinach'],
|
||||
['Dairy', 'Milk', 'Cheese', 'Yogurt'],
|
||||
];
|
||||
|
||||
console.log(shoppingList);
|
||||
|
||||
// Access to the second type of vegetable
|
||||
const secondVegetable = shoppingList[1][2]; // => 'Broccoli'
|
||||
console.log(shoppingList[1][3]); // => 'Spinach'
|
||||
|
||||
// ===============
|
||||
|
||||
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],
|
||||
],
|
||||
];
|
||||
|
||||
const inventoryObj = {
|
||||
floors: [
|
||||
{
|
||||
name: 'Electronics',
|
||||
shelfs: [
|
||||
{
|
||||
name: 'Shelf 1',
|
||||
products: [
|
||||
{
|
||||
name: 'Laptop',
|
||||
quantity: 10,
|
||||
},
|
||||
{
|
||||
name: 'Smartphone',
|
||||
quantity: 25,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
console.log(inventoryObj.floors[0].shelfs[0].products[0].quantity); // => 10
|
||||
|
||||
console.log(inventory[1][1][2]); // => 30
|
||||
|
||||
// Increase the number of laptops
|
||||
inventory[0][0][2] += 5; // New quantity: 15
|
||||
|
||||
// Add a new shelf to a category
|
||||
inventory[1].push(['Shelf 3', 'Pants', 20]);
|
||||
|
||||
console.log(inventory);
|
||||
|
||||
// ===============
|
||||
|
||||
// A small 2x2 image with RGB colors
|
||||
const image = [
|
||||
[
|
||||
// Row 1
|
||||
[255, 0, 0], // Pixel 1: Red
|
||||
[0, 255, 0], // Pixel 2: Green
|
||||
],
|
||||
[
|
||||
// Row 2
|
||||
[0, 0, 255], // Pixel 3: Blue
|
||||
[255, 255, 0], // Pixel 4: Yellow
|
||||
],
|
||||
];
|
||||
|
||||
console.log(image);
|
||||
|
||||
// Access to the green component of the second pixel
|
||||
const greenComponent = image[0][1][1]; // => 255
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,45 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Chess Vorlage</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">
|
||||
<h1>Chess Vorlage</h1>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const boardInStartPosition = [
|
||||
['♜', '♞', '♝', '♛', '♚', '♝', '♞', '♜'],
|
||||
['♟', '♟', '♟', '♟', '♟', '♟', '♟', '♟'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['♙', '♙', '♙', '♙', '♙', '♙', '♙', '♙'],
|
||||
['♖', '♘', '♗', '♕', '♔', '♗', '♘', '♖'],
|
||||
];
|
||||
|
||||
console.log('from: ', boardInStartPosition[7][6]); // => '♘'
|
||||
console.log('to: ', boardInStartPosition[5][5]);
|
||||
// Im Schachjargon: 'g1f3'
|
||||
|
||||
const emptyBoard = [
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
];
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,108 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Chess Move</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||
<style>
|
||||
.chess-board .chess-field {
|
||||
display: inline-block;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
padding: 0.5rem;
|
||||
border: 1px solid #efefef;
|
||||
text-align: center;
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<h1>Chess Move</h1>
|
||||
<div class="output alert alert-secondary my-3"></div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const outputEl = document.querySelector('.output');
|
||||
|
||||
// Damit das Array nicht versehentlich dauerhaft überschrieben werden kann, wird es in eine Funktion gepackt.
|
||||
const boardInStartPosition = () => [
|
||||
['♜', '♞', '♝', '♛', '♚', '♝', '♞', '♜'],
|
||||
['♟', '♟', '♟', '♟', '♟', '♟', '♟', '♟'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['♙', '♙', '♙', '♙', '♙', '♙', '♙', '♙'],
|
||||
['♖', '♘', '♗', '♕', '♔', '♗', '♘', '♖'],
|
||||
];
|
||||
|
||||
// console.log('from: ', boardInStartPosition()[7][6]); // => '♘'
|
||||
// console.log('to: ', boardInStartPosition()[5][5]);
|
||||
// Im Schachjargon: 'g1f3'
|
||||
|
||||
const emptyBoard = () => [
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
];
|
||||
|
||||
// Funktionen
|
||||
const originField = (move) => move.substring(0, 2); // => 'e2e4'-> 'e2'
|
||||
const targetField = (move) => move.substring(2); // => 'e2e4'-> 'e4'
|
||||
|
||||
const letterToChessIndex = (letter) => 'abcdefgh'.indexOf(letter);
|
||||
// => "e" -> 4 <- Array Spalte (x)
|
||||
const numberToChessIndex = (num) => 8 - num;
|
||||
// => '2' -> 6 <- Array Zeile (y)
|
||||
|
||||
const fieldToXPosition = (field) => letterToChessIndex(field.charAt(0));
|
||||
// => 'e2' -> 'e' -> letterToChessIndex('e') -> 4
|
||||
const fieldToYPosition = (field) => numberToChessIndex(field.charAt(1));
|
||||
// => 'e2' -> '2' -> numberToChessIndex('2') -> 6
|
||||
|
||||
const execMove = (board, move) => {
|
||||
const originX = fieldToXPosition(originField(move));
|
||||
// originField('e2e4') -> 'e2' -> fieldToXPosition('e2') -> 4 <- Array Spalte (x)
|
||||
const originY = fieldToYPosition(originField(move));
|
||||
// originField('e2e4') -> 'e2' -> fieldToYPosition('e2') -> 6 <- Array Zeile (y)
|
||||
const targetX = fieldToXPosition(targetField(move));
|
||||
// targetField('e2e4') -> 'e4' -> fieldToXPosition('e4') -> 4 <- Array Spalte (x)
|
||||
const targetY = fieldToYPosition(targetField(move));
|
||||
// targetField('e2e4') -> 'e4' -> fieldToYPosition('e4') -> 4 <- Array Zeile (y)
|
||||
|
||||
// board[4][4] = board[6][4]
|
||||
board[targetY][targetX] = board[originY][originX];
|
||||
|
||||
// board[6][4]
|
||||
board[originY][originX] = emptyBoard()[originY][originX];
|
||||
|
||||
return board;
|
||||
};
|
||||
|
||||
// 2 dimensionales Array als String mit Zeilenumbrüchen
|
||||
const board2string = (board) => board.map((row) => row.join(' ')).join('\n');
|
||||
|
||||
// 2 dimensionales Array als HTML-Board ausgeben
|
||||
const board2Html = (board) => {
|
||||
return `<div class="chess-board">${board
|
||||
.map((row) => {
|
||||
return `<div class="chess-row"><span class="chess-field">${row.join('</span><span class="chess-field">')}</span></div>`;
|
||||
})
|
||||
.join('')}</div>`;
|
||||
};
|
||||
|
||||
console.log(board2string(execMove(boardInStartPosition(), 'e2e4')));
|
||||
outputEl.innerHTML = board2Html(execMove(boardInStartPosition(), 'e2e4'));
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,122 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Chess Moves</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||
<style>
|
||||
.chess-board .chess-field {
|
||||
display: inline-block;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
padding: 0.5rem;
|
||||
border: 1px solid #efefef;
|
||||
text-align: center;
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<h1>Chess Move</h1>
|
||||
<div class="output alert alert-secondary my-3"></div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const outputEl = document.querySelector('.output');
|
||||
|
||||
// Damit das Array nicht versehentlich dauerhaft überschrieben werden kann, wird es in eine Funktion gepackt.
|
||||
const boardInStartPosition = () => [
|
||||
['♜', '♞', '♝', '♛', '♚', '♝', '♞', '♜'],
|
||||
['♟', '♟', '♟', '♟', '♟', '♟', '♟', '♟'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['♙', '♙', '♙', '♙', '♙', '♙', '♙', '♙'],
|
||||
['♖', '♘', '♗', '♕', '♔', '♗', '♘', '♖'],
|
||||
];
|
||||
|
||||
// console.log('from: ', boardInStartPosition()[7][6]); // => '♘'
|
||||
// console.log('to: ', boardInStartPosition()[5][5]);
|
||||
// Im Schachjargon: 'g1f3'
|
||||
|
||||
const emptyBoard = () => [
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
];
|
||||
|
||||
// Funktionen
|
||||
const originField = (move) => move.substring(0, 2); // => 'e2e4'-> 'e2'
|
||||
const targetField = (move) => move.substring(2); // => 'e2e4'-> 'e4'
|
||||
|
||||
const letterToChessIndex = (letter) => 'abcdefgh'.indexOf(letter);
|
||||
// => "e" -> 4 <- Array Spalte (x)
|
||||
const numberToChessIndex = (num) => 8 - num;
|
||||
// => '2' -> 6 <- Array Zeile (y)
|
||||
|
||||
const fieldToXPosition = (field) => letterToChessIndex(field.charAt(0));
|
||||
// => 'e2' -> 'e' -> letterToChessIndex('e') -> 4
|
||||
const fieldToYPosition = (field) => numberToChessIndex(field.charAt(1));
|
||||
// => 'e2' -> '2' -> numberToChessIndex('2') -> 6
|
||||
|
||||
const execMove = (board, move) => {
|
||||
const originX = fieldToXPosition(originField(move));
|
||||
// originField('e2e4') -> 'e2' -> fieldToXPosition('e2') -> 4 <- Array Spalte (x)
|
||||
const originY = fieldToYPosition(originField(move));
|
||||
// originField('e2e4') -> 'e2' -> fieldToYPosition('e2') -> 6 <- Array Zeile (y)
|
||||
const targetX = fieldToXPosition(targetField(move));
|
||||
// targetField('e2e4') -> 'e4' -> fieldToXPosition('e4') -> 4 <- Array Spalte (x)
|
||||
const targetY = fieldToYPosition(targetField(move));
|
||||
// targetField('e2e4') -> 'e4' -> fieldToYPosition('e4') -> 4 <- Array Zeile (y)
|
||||
|
||||
// board[4][4] = board[6][4]
|
||||
board[targetY][targetX] = board[originY][originX];
|
||||
|
||||
// board[6][4]
|
||||
board[originY][originX] = emptyBoard()[originY][originX];
|
||||
|
||||
return board;
|
||||
};
|
||||
|
||||
const execMoves = (moves = []) => {
|
||||
// [[BOARD],'e2e4', 'e7e5', 'f2f4'].reduce((board, move) => {
|
||||
// return execMove(board, move)
|
||||
// }, BOARD_ARRAY)
|
||||
|
||||
// return moves.reduce(execMove, boardInStartPosition()) // Funktionsreferenz auf execMove
|
||||
return moves.reduce((board, move) => execMove(board, move), boardInStartPosition());
|
||||
};
|
||||
|
||||
// 2 dimensionales Array als String mit Zeilenumbrüchen
|
||||
const board2string = (board) => board.map((row) => row.join(' ')).join('\n');
|
||||
|
||||
// 2 dimensionales Array als HTML-Board ausgeben
|
||||
const board2Html = (board) => {
|
||||
return `<div class="chess-board">${board
|
||||
.map((row) => {
|
||||
return `<div class="chess-row"><span class="chess-field">${row.join('</span><span class="chess-field">')}</span></div>`;
|
||||
})
|
||||
.join('')}</div>`;
|
||||
};
|
||||
|
||||
// 1 Spielzug visualisiert
|
||||
// console.log(board2string(execMove(boardInStartPosition(), 'e2e4')));
|
||||
// outputEl.innerHTML = board2Html(execMove(boardInStartPosition(), 'e2e4'));
|
||||
|
||||
// Mehrere Spielzüge visualisiert
|
||||
console.log(board2string(execMoves(['e2e4', 'e7e5', 'f2f4'])));
|
||||
outputEl.innerHTML = board2Html(execMoves(['e2e4', 'e7e5', 'f2f4']));
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,30 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>History Values in einem Array bleiben</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">
|
||||
<h1>History Values in einem Array bleiben</h1>
|
||||
<p>Alle vergangenen Schachzüge sollen in einer Array Position vorliegen</p>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const getMovesHistoryArray = (moves = []) => {
|
||||
// ['e2e4', 'e7e5', 'f2f4']
|
||||
return moves.map((cv, idx, ar) => {
|
||||
return ar.slice(0, idx + 1);
|
||||
});
|
||||
};
|
||||
|
||||
console.log(getMovesHistoryArray(['e2e4', 'e7e5', 'f2f4']));
|
||||
// => [['e2e4'], ['e2e4', 'e7e5'], ['e2e4', 'e7e5', 'f2f4']]
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,142 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Chess Moves</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||
<style>
|
||||
.chess-board .chess-field {
|
||||
display: inline-block;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
padding: 0.5rem;
|
||||
border: 1px solid #efefef;
|
||||
text-align: center;
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<h1>Chess Move</h1>
|
||||
<div class="output alert alert-secondary my-3"></div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const outputEl = document.querySelector('.output');
|
||||
|
||||
// Damit das Array nicht versehentlich dauerhaft überschrieben werden kann, wird es in eine Funktion gepackt.
|
||||
const boardInStartPosition = () => [
|
||||
['♜', '♞', '♝', '♛', '♚', '♝', '♞', '♜'],
|
||||
['♟', '♟', '♟', '♟', '♟', '♟', '♟', '♟'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['♙', '♙', '♙', '♙', '♙', '♙', '♙', '♙'],
|
||||
['♖', '♘', '♗', '♕', '♔', '♗', '♘', '♖'],
|
||||
];
|
||||
|
||||
// console.log('from: ', boardInStartPosition()[7][6]); // => '♘'
|
||||
// console.log('to: ', boardInStartPosition()[5][5]);
|
||||
// Im Schachjargon: 'g1f3'
|
||||
|
||||
const emptyBoard = () => [
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
['◻', '▦', '◻', '▦', '◻', '▦', '◻', '▦'],
|
||||
['▦', '◻', '▦', '◻', '▦', '◻', '▦', '◻'],
|
||||
];
|
||||
|
||||
// Funktionen
|
||||
const originField = (move) => move.substring(0, 2); // => 'e2e4'-> 'e2'
|
||||
const targetField = (move) => move.substring(2); // => 'e2e4'-> 'e4'
|
||||
|
||||
const letterToChessIndex = (letter) => 'abcdefgh'.indexOf(letter);
|
||||
// => "e" -> 4 <- Array Spalte (x)
|
||||
const numberToChessIndex = (num) => 8 - num;
|
||||
// => '2' -> 6 <- Array Zeile (y)
|
||||
|
||||
const fieldToXPosition = (field) => letterToChessIndex(field.charAt(0));
|
||||
// => 'e2' -> 'e' -> letterToChessIndex('e') -> 4
|
||||
const fieldToYPosition = (field) => numberToChessIndex(field.charAt(1));
|
||||
// => 'e2' -> '2' -> numberToChessIndex('2') -> 6
|
||||
|
||||
const getMovesHistoryArray = (moves = []) => {
|
||||
// ['e2e4', 'e7e5', 'f2f4']
|
||||
return moves.map((cv, idx, ar) => {
|
||||
return ar.slice(0, idx + 1);
|
||||
});
|
||||
};
|
||||
|
||||
const execMove = (board, move) => {
|
||||
const originX = fieldToXPosition(originField(move));
|
||||
// originField('e2e4') -> 'e2' -> fieldToXPosition('e2') -> 4 <- Array Spalte (x)
|
||||
const originY = fieldToYPosition(originField(move));
|
||||
// originField('e2e4') -> 'e2' -> fieldToYPosition('e2') -> 6 <- Array Zeile (y)
|
||||
const targetX = fieldToXPosition(targetField(move));
|
||||
// targetField('e2e4') -> 'e4' -> fieldToXPosition('e4') -> 4 <- Array Spalte (x)
|
||||
const targetY = fieldToYPosition(targetField(move));
|
||||
// targetField('e2e4') -> 'e4' -> fieldToYPosition('e4') -> 4 <- Array Zeile (y)
|
||||
|
||||
// board[4][4] = board[6][4]
|
||||
board[targetY][targetX] = board[originY][originX];
|
||||
|
||||
// board[6][4]
|
||||
board[originY][originX] = emptyBoard()[originY][originX];
|
||||
|
||||
return board;
|
||||
};
|
||||
|
||||
const execMoves = (moves = []) => {
|
||||
// ['e2e4', 'e7e5', 'f2f4'].reduce((board, move) => {
|
||||
// return execMove(board, move)
|
||||
// }, BOARD_ARRAY)
|
||||
|
||||
// return moves.reduce(execMove, boardInStartPosition()) // Funktionsreferenz auf execMove
|
||||
return moves.reduce((board, move) => execMove(board, move), boardInStartPosition());
|
||||
};
|
||||
|
||||
// 2 dimensionales Array als String mit Zeilenumbrüchen
|
||||
const board2string = (board) => board.map((row) => row.join(' ')).join('\n');
|
||||
|
||||
// 2 dimensionales Array als HTML-Board ausgeben
|
||||
const board2Html = (board) => {
|
||||
return `<div class="chess-board">${board
|
||||
.map((row) => {
|
||||
return `<div class="chess-row"><span class="chess-field">${row.join('</span><span class="chess-field">')}</span></div>`;
|
||||
})
|
||||
.join('')}</div>`;
|
||||
};
|
||||
|
||||
// 1 Spielzug visualisiert
|
||||
// console.log(board2string(execMove(boardInStartPosition(), 'e2e4')));
|
||||
// outputEl.innerHTML = board2Html(execMove(boardInStartPosition(), 'e2e4'));
|
||||
|
||||
// Mehrere Spielzüge visualisiert
|
||||
// console.log(board2string(execMoves(['e2e4', 'e7e5', 'f2f4'])));
|
||||
// outputEl.innerHTML = board2Html(execMoves(['e2e4', 'e7e5', 'f2f4']));
|
||||
|
||||
// Mehrere Spielzüge visualiert (Jedes Board einzelnd)
|
||||
const allMoves = getMovesHistoryArray(['e2e4', 'e7e5', 'f2f4']);
|
||||
// => [['e2e4'], ['e2e4', 'e7e5'], ['e2e4', 'e7e5', 'f2f4']]
|
||||
|
||||
outputEl.innerHTML = '';
|
||||
allMoves.forEach((moves) => {
|
||||
outputEl.innerHTML += board2Html(execMoves(moves));
|
||||
outputEl.innerHTML += '<hr />';
|
||||
|
||||
console.log(board2string(execMoves(moves)));
|
||||
console.log('=======================');
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,37 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Fetch API</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">
|
||||
<h1>Fetch API</h1>
|
||||
<p>
|
||||
Die <a href="https://developer.mozilla.org/de/docs/Web/API/Fetch_API">Fetch</a> API bietet eine Schnittstelle
|
||||
zum Abrufen von Ressourcen (einschließlich über das Netzwerk). Sie ist ein leistungsfähigerer und flexiblerer
|
||||
Ersatz für <code>XMLHttpRequest</code>.
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
fetch('https://dummyjson.com/posts')
|
||||
.then((response) => {
|
||||
console.log(response); // HTTP-Response Object
|
||||
return response.json(); // HTTP-Response Body -> ReadStream wird asynchron verarbeitet -> Promise
|
||||
})
|
||||
.then((data) => {
|
||||
console.log(data); // JSON als JS-Objekte geparsed
|
||||
console.log(data.posts[0].title); // => His mother had always taught him
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('Fetch operation error: ', err);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,56 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Fetch API</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">
|
||||
<h1>Fetch API</h1>
|
||||
<p>
|
||||
Die <a href="https://developer.mozilla.org/de/docs/Web/API/Fetch_API">Fetch</a> API bietet eine Schnittstelle
|
||||
zum Abrufen von Ressourcen (einschließlich über das Netzwerk). Sie ist ein leistungsfähigerer und flexiblerer
|
||||
Ersatz für <code>XMLHttpRequest</code>.
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
// Funktion mit async Prozess
|
||||
const getPosts = () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
fetch('https://dummyjson.com/posts')
|
||||
.then((response) => {
|
||||
console.log(response); // HTTP-Response Object
|
||||
return response.json(); // HTTP-Response Body -> ReadStream wird asynchron verarbeitet -> Promise
|
||||
})
|
||||
.then((data) => {
|
||||
// console.log(data); // JSON als JS-Objekte geparsed
|
||||
resolve(data);
|
||||
// z.B. generateArticles(data);
|
||||
})
|
||||
.catch((err) => {
|
||||
// console.error('Fetch operation error: ', err);
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Funktionsaufruf
|
||||
getPosts()
|
||||
.then((data) => {
|
||||
console.log(data);
|
||||
console.log(data.posts[0].title); // => His mother had always taught him
|
||||
|
||||
// z.B. generateArticles(data);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('Fetch operation error: ', err);
|
||||
});
|
||||
</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>Fetch API</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">
|
||||
<h1>Fetch API</h1>
|
||||
<p>
|
||||
Die <a href="https://developer.mozilla.org/de/docs/Web/API/Fetch_API">Fetch</a> API bietet eine Schnittstelle
|
||||
zum Abrufen von Ressourcen (einschließlich über das Netzwerk). Sie ist ein leistungsfähigerer und flexiblerer
|
||||
Ersatz für <code>XMLHttpRequest</code>.
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
// Funktion mit async Prozess
|
||||
const getPosts = async () => {
|
||||
try {
|
||||
const response = await fetch('https://dummyjson.com/posts');
|
||||
if (!response.ok) {
|
||||
throw new Error('HTTP-Response error');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
// console.log(data)
|
||||
return data; // => Rückgabe ist async -> Promise
|
||||
} catch (error) {
|
||||
console.error('Fetch operation error: ', error);
|
||||
return error; // => Rückgabe ist async -> Promise
|
||||
}
|
||||
};
|
||||
|
||||
// Funktionsaufruf
|
||||
getPosts()
|
||||
.then((data) => {
|
||||
console.log(data);
|
||||
console.log(data.posts[0].title); // => His mother had always taught him
|
||||
|
||||
// z.B. generateArticles(data);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('Fetch operation error: ', err);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,49 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>JSON.stringify() & JSON.parse()</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">
|
||||
<h1>JSON.stringify() & JSON.parse()</h1>
|
||||
<p>
|
||||
Im Gegensatz zu den meisten globalen Objekten ist
|
||||
<a href="https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON">JSON</a> kein
|
||||
Konstruktor. Sie können es nicht mit dem new Operator verwenden oder das JSON Objekt als Funktion aufrufen.
|
||||
Alle Eigenschaften und Methoden von JSON sind statisch (genau wie das Math Objekt).
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const person = {
|
||||
name: 'John Doe',
|
||||
age: 30, //
|
||||
lauf() {
|
||||
console.log('Ich laufe');
|
||||
},
|
||||
profession: 'Web Developer',
|
||||
};
|
||||
|
||||
// Convert JavaScript object to JSON string
|
||||
const jsonString = JSON.stringify(person);
|
||||
|
||||
console.log(jsonString);
|
||||
// => {"name":"John Doe","age":30,"profession":"Web Developer"}
|
||||
|
||||
try {
|
||||
// Convert JSON string back to JavaScript object
|
||||
const parsedPerson = JSON.parse(jsonString);
|
||||
console.log(parsedPerson.name); // => John Doe
|
||||
console.log(parsedPerson.age); // => 30
|
||||
} catch (error) {
|
||||
console.error('Invalid JSON:', error);
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,26 +0,0 @@
|
||||
[
|
||||
{
|
||||
"name": "Anna",
|
||||
"scores": [
|
||||
{ "name": "Mathematics", "score": 85 },
|
||||
{ "name": "English", "score": 92 },
|
||||
{ "name": "Biology", "score": 78 }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Ben",
|
||||
"scores": [
|
||||
{ "name": "Mathematics", "score": 76 },
|
||||
{ "name": "English", "score": 95 },
|
||||
{ "name": "Biology", "score": 89 }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Clara",
|
||||
"scores": [
|
||||
{ "name": "Mathematics", "score": 85 },
|
||||
{ "name": "English", "score": 92 },
|
||||
{ "name": "Biology", "score": 78 }
|
||||
]
|
||||
}
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user