This commit is contained in:
@@ -27,8 +27,8 @@
|
||||
|
||||
const isLibraryUpdating = false;
|
||||
const isUserLoggedIn = true;
|
||||
const hasLibrarianPermissions = true;
|
||||
const hasBookEditCapability = false;
|
||||
const hasLibrarianPermissions = false;
|
||||
const hasBookEditCapability = true;
|
||||
const hasBookAccess = false;
|
||||
|
||||
const bookCollection = [
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.css" />
|
||||
<title>Exercise: Nested If-Statements</title>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<h1>Exercise: Nested If-Statements</h1>
|
||||
<hr />
|
||||
<div class="alert alert-primary">
|
||||
<h2>Übung 1: Bibliotheksverwaltung</h2>
|
||||
<p>
|
||||
In dieser Übung besteht deine Aufgabe darin, die verschachtelten if-Anweisungen mit Hilfe der Inversion zu
|
||||
vereinfachen. In der nächsten Übung, in der du auch die Extraktion verwendest, wird deine Lösung verwendet.
|
||||
Verwende für diese Übung also nur die Inversion.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
let isLibraryUpdating = false;
|
||||
let isUserLoggedIn = true;
|
||||
let hasLibrarianPermissions = false;
|
||||
let hasBookEditCapability = true;
|
||||
let hasBookAccess = false;
|
||||
|
||||
const bookCollection = [
|
||||
{
|
||||
title: 'Book A',
|
||||
price: 150,
|
||||
quantity: 5,
|
||||
},
|
||||
{
|
||||
title: 'Book B',
|
||||
price: 250,
|
||||
quantity: 0,
|
||||
},
|
||||
{
|
||||
title: 'Book C',
|
||||
price: 350,
|
||||
quantity: 10,
|
||||
},
|
||||
];
|
||||
|
||||
function handleLibraryOperations() {
|
||||
if (isLibraryUpdating) {
|
||||
console.log('Library system is currently updating.');
|
||||
return;
|
||||
}
|
||||
if (!isUserLoggedIn) {
|
||||
console.log('Please log in to manage books.');
|
||||
return;
|
||||
}
|
||||
if (!(hasLibrarianPermissions || (hasBookEditCapability && hasBookAccess))) {
|
||||
console.log('Insufficient rights to manage books.');
|
||||
return;
|
||||
}
|
||||
|
||||
bookCollection.forEach((book) => {
|
||||
console.log(`Book Title: ${book.title}`);
|
||||
if (book.price > 200) {
|
||||
console.log('Book price is greater than 200.');
|
||||
} else {
|
||||
console.log('Book price is less than or equal to 200.');
|
||||
}
|
||||
if (book.quantity > 0) {
|
||||
console.log('Book is available.');
|
||||
} else {
|
||||
console.log('Book is unavailable.');
|
||||
}
|
||||
console.log('---');
|
||||
});
|
||||
}
|
||||
handleLibraryOperations();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,100 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.css" />
|
||||
<title>Exercise: Nested If-Statements</title>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<h1>Exercise: Nested If-Statements</h1>
|
||||
<hr />
|
||||
<div class="alert alert-primary">
|
||||
<h2>Übung 2: Bibliotheksverwaltung – Extraktion</h2>
|
||||
<p>
|
||||
Diese Übung setzt voraus, dass du die Übung Bibliotheksverwaltung abgeschlossen hast. Du kannst deine eigene
|
||||
Lösung oder eine Musterlösung für die Übung verwenden.
|
||||
</p>
|
||||
<p>
|
||||
Diesmal machst du den Code lesbarer und übersichtlicher, indem du die Kernlogik in separate Funktionen
|
||||
extrahierst. Erstelle eine neue Datei, kopiere den Code hinein und wende das Extraktionskonzept an.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
'use strict';
|
||||
(() => {
|
||||
let isLibraryUpdating = false;
|
||||
let isUserLoggedIn = true;
|
||||
let hasLibrarianPermissions = false;
|
||||
let hasBookEditCapability = true;
|
||||
let hasBookAccess = true;
|
||||
|
||||
const bookCollection = [
|
||||
{ title: 'Book A', price: 150, quantity: 5 },
|
||||
{ title: 'Book B', price: 250, quantity: 0 },
|
||||
{ title: 'Book C', price: 350, quantity: 10 },
|
||||
];
|
||||
|
||||
// init
|
||||
const init = () => {
|
||||
handleLibraryOperations();
|
||||
};
|
||||
|
||||
// Functions =======
|
||||
|
||||
const handleLibraryOperations = () => {
|
||||
if (isLibraryUpdating) {
|
||||
console.log('Library system is currently updating.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isUserLoggedIn) {
|
||||
console.log('Please log in to manage books.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasPermissions()) {
|
||||
console.log('Insufficient rights to manage books.');
|
||||
return;
|
||||
}
|
||||
|
||||
bookCollection.forEach(logBook);
|
||||
};
|
||||
|
||||
const logBook = (book) => {
|
||||
console.log(`Book Title: ${book.title}`);
|
||||
logBookPrice(book);
|
||||
logBookAvailability(book);
|
||||
console.log('---');
|
||||
};
|
||||
|
||||
const logBookPrice = (book, threshold = 200) => {
|
||||
if (book.price > threshold) {
|
||||
console.log(`Book price is greater than ${threshold}.`);
|
||||
} else {
|
||||
console.log(`Book price is less than or equal to ${threshold}.`);
|
||||
}
|
||||
};
|
||||
|
||||
const logBookAvailability = (book, stockAmount = 0) => {
|
||||
if (book.quantity > stockAmount) {
|
||||
console.log('Book is available.');
|
||||
} else {
|
||||
console.log('Book is unavailable.');
|
||||
}
|
||||
};
|
||||
|
||||
const hasPermissions = () => {
|
||||
return hasLibrarianPermissions || (hasBookEditCapability && hasBookAccess);
|
||||
};
|
||||
|
||||
init();
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,71 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.css" />
|
||||
<title>Übung 3: DRY</title>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<h1>Exercise: Don't Repeat Yourself (DRY)</h1>
|
||||
<hr />
|
||||
<div class="alert alert-primary">
|
||||
<h2>Übung 3: DRY</h2>
|
||||
<p>
|
||||
In dieser Übung überarbeitest du einen Teil des Codes nach dem DRY-Prinzip (Don't Repeat Yourself). Du
|
||||
arbeitest mit einem Skript, das Wetterberichte für mehrere Städte protokolliert, einschließlich zusätzlicher
|
||||
Wetterdaten wie der Windgeschwindigkeit. Deine Aufgabe ist es, Code-Wiederholungen zu vermeiden, indem du
|
||||
Arrays, Schleifen und Funktionen verwendest.
|
||||
</p>
|
||||
<p>
|
||||
Erstelle eine zusätzliche <code>formatWeatherReport(report)</code> Funktion, die ein Wetterberichtsobjekt
|
||||
als Parameter annimmt. Sie sollte einen formatierten Wetterberichtstring zurückgeben.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const weatherReports = [
|
||||
{
|
||||
city: 'New York',
|
||||
temperature: 85,
|
||||
humidity: 70,
|
||||
description: 'Sunny',
|
||||
windSpeed: 10,
|
||||
},
|
||||
{
|
||||
city: 'Los Angeles',
|
||||
temperature: 75,
|
||||
humidity: 60,
|
||||
description: 'Partly Cloudy',
|
||||
windSpeed: 7,
|
||||
},
|
||||
{
|
||||
city: 'Chicago',
|
||||
temperature: 70,
|
||||
humidity: 65,
|
||||
description: 'Rainy',
|
||||
windSpeed: 12,
|
||||
},
|
||||
];
|
||||
|
||||
function formatWeatherReport(report) {
|
||||
const { city, temperature, humidity, description, windSpeed } = report;
|
||||
return `Weather in ${city}: ${temperature}°F, ${humidity}% humidity, ${description}, Wind Speed: ${windSpeed}mph`;
|
||||
}
|
||||
|
||||
function logWeatherReports(reports) {
|
||||
reports.forEach((report) => {
|
||||
console.log(formatWeatherReport(report));
|
||||
});
|
||||
}
|
||||
|
||||
logWeatherReports(weatherReports);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,295 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Advanced If-Else Statements (Enhanced Nesting)</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>Advanced If-Else Statements (Enhanced Nesting)</h1>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const AVAILABLE_USER_ROLES = ['admin', 'editor', 'viewer'];
|
||||
const AVAILABLE_USER_DEPARTMENTS = ['engineering', 'marketing', 'sales'];
|
||||
|
||||
// IIIFE
|
||||
(() => {
|
||||
let isSystemUnderMaintenance = false;
|
||||
let isUserAuthenticated = true;
|
||||
let userRole = 'editor'; // Possible roles: 'admin', 'editor', 'viewer'
|
||||
let hasPremiumAccess = false;
|
||||
let hasTwoFactorAuth = true;
|
||||
let accountStatus = 'active'; // Possible statuses: 'active', 'suspended', 'closed'
|
||||
let userDepartment = 'marketing'; // Possible departments: 'engineering', 'marketing', 'sales'
|
||||
|
||||
const userActions = [
|
||||
{
|
||||
action: 'viewDashboard',
|
||||
requiresAdmin: false,
|
||||
requiresPremium: false,
|
||||
allowedDepartments: ['engineering', 'marketing', 'sales'],
|
||||
},
|
||||
{
|
||||
action: 'editContent',
|
||||
requiresAdmin: false,
|
||||
requiresPremium: true,
|
||||
allowedDepartments: ['marketing'],
|
||||
},
|
||||
{
|
||||
action: 'manageUsers',
|
||||
requiresAdmin: true,
|
||||
requiresPremium: false,
|
||||
allowedDepartments: ['engineering'],
|
||||
},
|
||||
{
|
||||
action: 'accessAnalytics',
|
||||
requiresAdmin: true,
|
||||
requiresPremium: true,
|
||||
allowedDepartments: ['sales', 'marketing'],
|
||||
},
|
||||
{
|
||||
action: 'deployCode',
|
||||
requiresAdmin: true,
|
||||
requiresPremium: true,
|
||||
allowedDepartments: ['engineering'],
|
||||
},
|
||||
];
|
||||
|
||||
const fulfillsRequirements = () => {
|
||||
if (isSystemUnderMaintenance) {
|
||||
console.log('System is under maintenance. Please try again later.');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isUserAuthenticated) {
|
||||
console.log('User is not authenticated. Redirecting to login page.');
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const accountIsActive = (status) => {
|
||||
switch (status) {
|
||||
case 'active':
|
||||
return true;
|
||||
|
||||
case 'closed':
|
||||
console.log('Account is closed. Access denied.');
|
||||
return false;
|
||||
|
||||
case 'suspended':
|
||||
console.log('Account is suspended. Contact support.');
|
||||
return false;
|
||||
|
||||
default:
|
||||
console.log('Unknown account status.');
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const isAvailableUserRole = (userRole) => {
|
||||
return AVAILABLE_USER_ROLES.includes(userRole);
|
||||
};
|
||||
|
||||
const isAvailableUserDepartment = (userDepartment) => {
|
||||
return AVAILABLE_USER_DEPARTMENTS.includes(userDepartment);
|
||||
};
|
||||
|
||||
const processAdminRole = () => {
|
||||
if (!isAvailableUserDepartment(userDepartment)) {
|
||||
console.log('Unknown department. Access denied.');
|
||||
return;
|
||||
}
|
||||
|
||||
userActions.forEach((action) => {
|
||||
if (action.allowedDepartments.includes(userDepartment)) {
|
||||
console.log(`Admin (${userDepartment}) accessing: ${action.action}`);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const processEditorRole = () => {
|
||||
if (!hasPremiumAccess) {
|
||||
console.log('Premium access required to edit content.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (userDepartment !== 'marketing') {
|
||||
console.log('Editors are only allowed in the Marketing department.');
|
||||
return;
|
||||
}
|
||||
|
||||
userActions.forEach((action) => {
|
||||
if (action.requiresPremium && action.allowedDepartments.includes(userDepartment)) {
|
||||
console.log(`Editor (${userDepartment}) accessing: ${action.action}`);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const processViewerRole = () => {
|
||||
if (userDepartment !== 'sales') {
|
||||
console.log('Viewers are only allowed in the Sales department.');
|
||||
return;
|
||||
}
|
||||
|
||||
userActions.forEach((action) => {
|
||||
if (
|
||||
!action.requiresAdmin &&
|
||||
!action.requiresPremium &&
|
||||
action.allowedDepartments.includes(userDepartment)
|
||||
) {
|
||||
console.log(`Viewer (${userDepartment}) accessing: ${action.action}`);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const manageUserAccess = () => {
|
||||
if (!fulfillsRequirements()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!accountIsActive(accountStatus)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasTwoFactorAuth) {
|
||||
console.log('Two-Factor Authentication is required for access.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isAvailableUserRole(userRole)) {
|
||||
console.log('Unknown user role. Access denied.');
|
||||
return;
|
||||
}
|
||||
|
||||
switch (userRole) {
|
||||
case 'admin':
|
||||
processAdminRole();
|
||||
return;
|
||||
|
||||
case 'editor':
|
||||
processEditorRole();
|
||||
return;
|
||||
|
||||
case 'viewer':
|
||||
processViewerRole();
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// ===== TEST CASES =====
|
||||
|
||||
// Test Case 1: System Under Maintenance
|
||||
console.warn('Test Case 1: System Under Maintenance');
|
||||
isSystemUnderMaintenance = true;
|
||||
manageUserAccess(); // => "System is under maintenance. Please try again later."
|
||||
resetVariables();
|
||||
|
||||
// Test Case 2: User Not Authenticated
|
||||
console.warn('Test Case 2: User Not Authenticated');
|
||||
isSystemUnderMaintenance = false;
|
||||
isUserAuthenticated = false;
|
||||
manageUserAccess(); // => "User is not authenticated. Redirecting to login page."
|
||||
resetVariables();
|
||||
|
||||
// Test Case 3: Account Suspended
|
||||
console.warn('Test Case 3: Account Suspended');
|
||||
hasTwoFactorAuth = false;
|
||||
accountStatus = 'suspended';
|
||||
manageUserAccess(); // => "Account is suspended. Contact support."
|
||||
resetVariables();
|
||||
|
||||
// Test Case 4: Missing Two-Factor Authentication
|
||||
console.warn('Test Case 4: Missing Two-Factor Authentication');
|
||||
hasTwoFactorAuth = false;
|
||||
accountStatus = 'active';
|
||||
manageUserAccess(); // => "Two-Factor Authentication is required for access."
|
||||
resetVariables();
|
||||
|
||||
// Test Case 5: Admin Access in Marketing Department
|
||||
console.warn('Test Case 5: Admin Access in Marketing Department');
|
||||
userRole = 'admin';
|
||||
userDepartment = 'marketing';
|
||||
manageUserAccess();
|
||||
// Expected Output:
|
||||
// "Admin (marketing) accessing: viewDashboard"
|
||||
// "Admin (marketing) accessing: editContent"
|
||||
// "Admin (marketing) accessing: accessAnalytics"
|
||||
resetVariables();
|
||||
|
||||
// Test Case 6: Editor Without Premium Access
|
||||
console.warn('Test Case 6: Editor Without Premium Access');
|
||||
userRole = 'editor';
|
||||
hasPremiumAccess = false;
|
||||
manageUserAccess(); // => "Premium access required to edit content."
|
||||
resetVariables();
|
||||
|
||||
// Test Case 7: Editor With Premium Access in Marketing Department
|
||||
console.warn('Test Case 7: Editor With Premium Access in Marketing Department');
|
||||
hasPremiumAccess = true;
|
||||
manageUserAccess();
|
||||
// Expected Output:
|
||||
// "Editor (marketing) accessing: editContent"
|
||||
// "Editor (marketing) accessing: accessAnalytics"
|
||||
resetVariables();
|
||||
|
||||
// Test Case 8: Viewer Access in Sales Department
|
||||
console.warn('Test Case 8: Viewer Access in Sales Department');
|
||||
userRole = 'viewer';
|
||||
userDepartment = 'sales';
|
||||
manageUserAccess(); // => "Viewer (sales) accessing: viewDashboard"
|
||||
resetVariables();
|
||||
|
||||
// Test Case 9: Unknown User Role
|
||||
console.warn('Test Case 9: Unknown User Role');
|
||||
userRole = 'guest';
|
||||
manageUserAccess(); // => "Unknown user role. Access denied."
|
||||
resetVariables();
|
||||
|
||||
// Test Case 10: Viewer Access in Marketing Department
|
||||
console.warn('Test Case 10: Viewer Access in Marketing Department');
|
||||
userRole = 'viewer';
|
||||
userDepartment = 'marketing';
|
||||
manageUserAccess(); // => "Viewers are only allowed in the Sales department."
|
||||
resetVariables();
|
||||
|
||||
// Test Case 11: Admin Access in Engineering Department
|
||||
console.warn('Test Case 11: Admin Access in Engineering Department');
|
||||
userRole = 'admin';
|
||||
userDepartment = 'engineering';
|
||||
manageUserAccess();
|
||||
// Expected Output:
|
||||
// "Admin (engineering) accessing: viewDashboard"
|
||||
// "Admin (engineering) accessing: manageUsers"
|
||||
// "Admin (engineering) accessing: deployCode"
|
||||
resetVariables();
|
||||
|
||||
// Test Case 12: Editor With Premium Access in Engineering Department
|
||||
console.warn('Test Case 12: Editor With Premium Access in Engineering Department');
|
||||
userRole = 'editor';
|
||||
hasPremiumAccess = true;
|
||||
userDepartment = 'engineering';
|
||||
manageUserAccess(); // => "Editors are only allowed in the Marketing department."
|
||||
resetVariables();
|
||||
|
||||
// ===== HELPER FUNCTION =====
|
||||
function resetVariables() {
|
||||
isSystemUnderMaintenance = false;
|
||||
isUserAuthenticated = true;
|
||||
userRole = 'editor';
|
||||
hasPremiumAccess = false;
|
||||
hasTwoFactorAuth = true;
|
||||
accountStatus = 'active';
|
||||
userDepartment = 'marketing';
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,273 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.css" />
|
||||
<title>Übung 4: Benutzerzugang verwalten</title>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<h1>Advanced If-Else Statements (Enhanced Nesting)</h1>
|
||||
<hr />
|
||||
<div class="alert alert-primary">
|
||||
<h2>Übung 4: Benutzerzugang verwalten</h2>
|
||||
<p>
|
||||
In dieser Übung ist es deine Aufgabe, den folgenden Code zu vereinfachen und dabei alle Techniken und
|
||||
Prinzipien anzuwenden, die du bisher gelernt hast. Der vorgegebene Code simuliert ein
|
||||
Benutzerverwaltungssystem mit verschiedenen Berechtigungen und Zuständen. Dein Ziel ist es, die Funktion
|
||||
<code>manageUserAccess</code> zu überarbeiten, um die Logik sauberer und lesbarer zu machen, indem du die
|
||||
Komplexität der verschachtelten Bedingungen reduzierst.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
let isSystemUnderMaintenance = false;
|
||||
let isUserAuthenticated = true;
|
||||
let userRole = 'editor'; // Possible roles: 'admin', 'editor', 'viewer'
|
||||
let hasPremiumAccess = false;
|
||||
let hasTwoFactorAuth = true;
|
||||
let accountStatus = 'active'; // Possible statuses: 'active', 'suspended', 'closed'
|
||||
let userDepartment = 'marketing'; // Possible departments: 'engineering', 'marketing', 'sales'
|
||||
|
||||
const userActions = [
|
||||
{
|
||||
action: 'viewDashboard',
|
||||
requiresAdmin: false,
|
||||
requiresPremium: false,
|
||||
allowedDepartments: ['engineering', 'marketing', 'sales'],
|
||||
},
|
||||
{
|
||||
action: 'editContent',
|
||||
requiresAdmin: false,
|
||||
requiresPremium: true,
|
||||
allowedDepartments: ['marketing'],
|
||||
},
|
||||
{
|
||||
action: 'manageUsers',
|
||||
requiresAdmin: true,
|
||||
requiresPremium: false,
|
||||
allowedDepartments: ['engineering'],
|
||||
},
|
||||
{
|
||||
action: 'accessAnalytics',
|
||||
requiresAdmin: true,
|
||||
requiresPremium: true,
|
||||
allowedDepartments: ['sales', 'marketing'],
|
||||
},
|
||||
{
|
||||
action: 'deployCode',
|
||||
requiresAdmin: true,
|
||||
requiresPremium: true,
|
||||
allowedDepartments: ['engineering'],
|
||||
},
|
||||
];
|
||||
|
||||
function isAccountStatusViable() {
|
||||
const statusMessages = {
|
||||
suspended: 'Account is suspended. Contact support.',
|
||||
closed: 'Account is closed. Access denied.',
|
||||
};
|
||||
|
||||
if (accountStatus !== 'active') {
|
||||
console.log(statusMessages[accountStatus] || 'Unknown account status.');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function isRole(role) {
|
||||
return userRole === role;
|
||||
}
|
||||
|
||||
function isDepartment(department) {
|
||||
return userDepartment === department;
|
||||
}
|
||||
|
||||
function logAccess(userType, options = {}) {
|
||||
const { blRequirePremium = null, blRequiresAdmin = null } = options;
|
||||
console.log(userType, options);
|
||||
|
||||
userActions.forEach((userAction) => {
|
||||
const { requiresPremium, requiresAdmin, action } = userAction;
|
||||
|
||||
if ((blRequirePremium === false && requiresPremium) || (blRequirePremium && !requiresPremium)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ((blRequiresAdmin === false && requiresAdmin) || (blRequiresAdmin && !requiresAdmin)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (allowedDepartments.includes(userDepartment)) {
|
||||
console.log(`${userType} (${userDepartment}) accessing: ${action}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function manageUserAccess() {
|
||||
if (isSystemUnderMaintenance) {
|
||||
console.log('System is under maintenance. Please try again later.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isUserAuthenticated) {
|
||||
console.log('User is not authenticated. Redirecting to login page.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isAccountStatusViable()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasTwoFactorAuth) {
|
||||
console.log('Two-Factor Authentication is required for access.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (isRole('admin')) {
|
||||
if (isDepartment('engineering') || isDepartment('marketing') || isDepartment('sales')) {
|
||||
logAccess('Admin');
|
||||
} else {
|
||||
console.log('Unknown department. Access denied.');
|
||||
}
|
||||
} else if (isRole('editor')) {
|
||||
if (!hasPremiumAccess) {
|
||||
console.log('Premium access required to edit content.');
|
||||
return;
|
||||
}
|
||||
if (isDepartment('marketing')) {
|
||||
logAccess('Editor', { blRequirePremium: true });
|
||||
} else {
|
||||
console.log('Editors are only allowed in the Marketing department.');
|
||||
return;
|
||||
}
|
||||
} else if (isRole('viewer')) {
|
||||
if (isDepartment('sales')) {
|
||||
logAccess('Viewer', {
|
||||
blRequirePremium: false,
|
||||
blRequiresAdmin: false,
|
||||
});
|
||||
} else {
|
||||
console.log('Viewers are only allowed in the Sales department.');
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
console.log('Unknown user role. Access denied.');
|
||||
}
|
||||
}
|
||||
|
||||
// ===== TEST CASES =====
|
||||
|
||||
// Test Case 1: System Under Maintenance
|
||||
console.warn('Test Case 1: System Under Maintenance');
|
||||
isSystemUnderMaintenance = true;
|
||||
manageUserAccess(); // => "System is under maintenance. Please try again later."
|
||||
resetVariables();
|
||||
|
||||
// Test Case 2: User Not Authenticated
|
||||
console.warn('Test Case 2: User Not Authenticated');
|
||||
isSystemUnderMaintenance = false;
|
||||
isUserAuthenticated = false;
|
||||
manageUserAccess(); // => "User is not authenticated. Redirecting to login page."
|
||||
resetVariables();
|
||||
|
||||
// Test Case 3: Account Suspended
|
||||
console.warn('Test Case 3: Account Suspended');
|
||||
hasTwoFactorAuth = false;
|
||||
accountStatus = 'suspended';
|
||||
manageUserAccess(); // => "Account is suspended. Contact support."
|
||||
resetVariables();
|
||||
|
||||
// Test Case 4: Missing Two-Factor Authentication
|
||||
console.warn('Test Case 4: Missing Two-Factor Authentication');
|
||||
hasTwoFactorAuth = false;
|
||||
accountStatus = 'active';
|
||||
manageUserAccess(); // => "Two-Factor Authentication is required for access."
|
||||
resetVariables();
|
||||
|
||||
// Test Case 5: Admin Access in Marketing Department
|
||||
console.warn('Test Case 5: Admin Access in Marketing Department');
|
||||
userRole = 'admin';
|
||||
userDepartment = 'marketing';
|
||||
manageUserAccess();
|
||||
// Expected Output:
|
||||
// "Admin (marketing) accessing: viewDashboard"
|
||||
// "Admin (marketing) accessing: editContent"
|
||||
// "Admin (marketing) accessing: accessAnalytics"
|
||||
resetVariables();
|
||||
|
||||
// Test Case 6: Editor Without Premium Access
|
||||
console.warn('Test Case 6: Editor Without Premium Access');
|
||||
userRole = 'editor';
|
||||
hasPremiumAccess = false;
|
||||
manageUserAccess(); // => "Premium access required to edit content."
|
||||
resetVariables();
|
||||
|
||||
// Test Case 7: Editor With Premium Access in Marketing Department
|
||||
console.warn('Test Case 7: Editor With Premium Access in Marketing Department');
|
||||
hasPremiumAccess = true;
|
||||
manageUserAccess();
|
||||
// Expected Output:
|
||||
// "Editor (marketing) accessing: editContent"
|
||||
// "Editor (marketing) accessing: accessAnalytics"
|
||||
resetVariables();
|
||||
|
||||
// Test Case 8: Viewer Access in Sales Department
|
||||
console.warn('Test Case 8: Viewer Access in Sales Department');
|
||||
userRole = 'viewer';
|
||||
userDepartment = 'sales';
|
||||
manageUserAccess(); // => "Viewer (sales) accessing: viewDashboard"
|
||||
resetVariables();
|
||||
|
||||
// Test Case 9: Unknown User Role
|
||||
console.warn('Test Case 9: Unknown User Role');
|
||||
userRole = 'guest';
|
||||
manageUserAccess(); // => "Unknown user role. Access denied."
|
||||
resetVariables();
|
||||
|
||||
// Test Case 10: Viewer Access in Marketing Department
|
||||
console.warn('Test Case 10: Viewer Access in Marketing Department');
|
||||
userRole = 'viewer';
|
||||
userDepartment = 'marketing';
|
||||
manageUserAccess(); // => "Viewers are only allowed in the Sales department."
|
||||
resetVariables();
|
||||
|
||||
// Test Case 11: Admin Access in Engineering Department
|
||||
console.warn('Test Case 11: Admin Access in Engineering Department');
|
||||
userRole = 'admin';
|
||||
userDepartment = 'engineering';
|
||||
manageUserAccess();
|
||||
// Expected Output:
|
||||
// "Admin (engineering) accessing: viewDashboard"
|
||||
// "Admin (engineering) accessing: manageUsers"
|
||||
// "Admin (engineering) accessing: deployCode"
|
||||
resetVariables();
|
||||
|
||||
// Test Case 12: Editor With Premium Access in Engineering Department
|
||||
console.warn('Test Case 12: Editor With Premium Access in Engineering Department');
|
||||
userRole = 'editor';
|
||||
hasPremiumAccess = true;
|
||||
userDepartment = 'engineering';
|
||||
manageUserAccess(); // => "Editors are only allowed in the Marketing department."
|
||||
resetVariables();
|
||||
|
||||
// ===== HELPER FUNCTION =====
|
||||
function resetVariables() {
|
||||
isSystemUnderMaintenance = false;
|
||||
isUserAuthenticated = true;
|
||||
userRole = 'editor';
|
||||
hasPremiumAccess = false;
|
||||
hasTwoFactorAuth = true;
|
||||
accountStatus = 'active';
|
||||
userDepartment = 'marketing';
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,30 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Übung 05: formatDate Fehler</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<div class="alert alert-primary">
|
||||
<h2>Übung 05: formatDate Fehler</h2>
|
||||
<p>Die Kommentare zeigen das erwartete Ergebnis.</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
function formatDate(date) {
|
||||
const options = { year: 'numeric', month: 'long', day: 'numeric' };
|
||||
const formatedDate = date.toLocaleDateString('en-US', options);
|
||||
return formatedDate;
|
||||
}
|
||||
|
||||
console.log(formatDate(new Date('2023-05-31'))); // => 'May 31, 2023'
|
||||
console.log(formatDate(new Date('2024-01-01'))); // => 'January 1, 2024'
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,57 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Übung 6: Benutzer erstellen</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<div class="alert alert-primary">
|
||||
<h2>Übung 6: Benutzer erstellen</h2>
|
||||
<p>
|
||||
Nehmen wir eine anspruchsvollere Syntaxfehlerübung in Angriff. Diese Übung enthält mehrere Syntaxfehler, die
|
||||
über den gesamten Code verteilt sind. Dein Ziel ist es, alle Syntaxfehler zu identifizieren und zu beheben,
|
||||
damit der Code korrekt ausgeführt werden kann.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
function createUser(name, email, age) {
|
||||
return {
|
||||
name,
|
||||
email,
|
||||
age,
|
||||
greet() {
|
||||
console.log(`Hello, ${this.name}!`);
|
||||
},
|
||||
updateEmail(newEmail) {
|
||||
this.email = newEmail;
|
||||
console.log(`Email updated to ${this.email}`);
|
||||
},
|
||||
};
|
||||
}
|
||||
const users = [
|
||||
createUser('Alice', 'alice@example.com', 30),
|
||||
createUser('Bob', 'bob@example.com', 25),
|
||||
createUser('Charlie', 'charlie@example.com', 35),
|
||||
];
|
||||
|
||||
users.forEach((user) => {
|
||||
user.greet();
|
||||
user.updateEmail(`new_${user.email}`);
|
||||
});
|
||||
|
||||
function calculateTotal(...numbers) {
|
||||
return numbers.reduce((sum, n) => sum + n, 0);
|
||||
}
|
||||
|
||||
console.log('Total:', calculateTotal(10, 20, 30));
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,41 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Übung 7: checkTemperature Fehler</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<div class="alert alert-primary">
|
||||
<h2>Übung 7: checkTemperature Fehler</h2>
|
||||
<p>Versuche, den Code auszuführen, den Fehler zu identifizieren und ihn zu beheben.</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const checkTemperature = (temperature) => {
|
||||
const threshold = 30;
|
||||
|
||||
// let message;
|
||||
|
||||
// if (temperature > threshold) {
|
||||
// message = "It's too hot outside!";
|
||||
// } else {
|
||||
// message = 'The temperature is just right.';
|
||||
// }
|
||||
|
||||
const message = temperature > threshold ? "It's too hot outside!" : 'The temperature is just right.';
|
||||
|
||||
return message;
|
||||
};
|
||||
|
||||
console.log(checkTemperature(25)); // => "The temperature is just right."
|
||||
console.log(checkTemperature(35)); // => "It's too hot outside!"
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,59 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Übung 8: Benutzer anzeigen</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<div class="alert alert-primary">
|
||||
<h2>Übung 8: Benutzer anzeigen</h2>
|
||||
<p>
|
||||
Der folgende Code enthält mehrere Referenzfehler, die über verschiedene Teile des Codes verteilt sind. Deine
|
||||
Aufgabe ist es, alle Referenzfehler zu identifizieren und zu beheben, um sicherzustellen, dass der Code
|
||||
korrekt läuft.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
const userName = 'Emily';
|
||||
const age = 88;
|
||||
|
||||
function displayUserInfo(user, age) {
|
||||
console.log('User Name: ', user);
|
||||
console.log('User Age: ', age);
|
||||
}
|
||||
|
||||
function updateEmail(newEmail) {
|
||||
const userEmail = newEmail;
|
||||
console.log(`Email updated to ${userEmail}`);
|
||||
}
|
||||
|
||||
function calculateBMI(weight, height) {
|
||||
return weight / (height * height);
|
||||
}
|
||||
|
||||
function greetUser(name) {
|
||||
if (name === 'Emily') {
|
||||
console.log('Welcome back, ' + name + '!');
|
||||
} else {
|
||||
console.log('Hello, ' + name + '!');
|
||||
}
|
||||
}
|
||||
|
||||
displayUserInfo(userName, age);
|
||||
updateEmail('emily@example.com');
|
||||
|
||||
const bmi = calculateBMI(70, 1.75);
|
||||
console.log('BMI:', bmi);
|
||||
|
||||
greetUser('Michael');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,40 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Übung 9: parseUserData Fehler</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="container py-5">
|
||||
<div class="alert alert-primary">
|
||||
<h2>Übung 9: parseUserData Fehler</h2>
|
||||
<p>Die Kommentare zeigen das erwartete Ergebnis.</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
'use strict';
|
||||
|
||||
function parseUserData(jsonString) {
|
||||
try {
|
||||
const userData = JSON.parse(jsonString);
|
||||
|
||||
if (typeof userData.name !== 'string' || typeof userData.age !== 'number') {
|
||||
throw new TypeError('Invalid data types');
|
||||
}
|
||||
|
||||
return `User: ${userData.name}, Age: ${userData.age}`;
|
||||
} catch (error) {
|
||||
console.log(error, error.name);
|
||||
return `Error: ${error.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(parseUserData('{"name": "Alice", "age": 30}')); // => 'User: Alice, Age: 30'
|
||||
console.log(parseUserData('{"name": "Bob", "age": "thirty"}')); // => 'Error: Invalid
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Übung 10: Einkaufspreis</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||
<script src="index.js" defer></script>
|
||||
<script src="solution.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
function calculateTotalPrice(items = []) {
|
||||
// let total = 0;
|
||||
// items.forEach((item) => {
|
||||
// total += item.price;
|
||||
// });
|
||||
const total = items.reduce((sum, item) => {
|
||||
// Ensure that item.price is a number
|
||||
const price = typeof item.price === 'number' ? item.price : Number(item.price);
|
||||
|
||||
if (isNaN(price)) {
|
||||
console.warn(`Invalid price for item "${item.name}". Skipping...`);
|
||||
return sum;
|
||||
}
|
||||
return sum + Number(item.price);
|
||||
}, 0);
|
||||
|
||||
return Number(total.toFixed(2));
|
||||
}
|
||||
|
||||
const shoppingCart = [
|
||||
{ name: 'Laptop', price: 999.99 },
|
||||
{ name: 'Smartphone', price: 599.99 },
|
||||
{ name: 'Headphones', cost: 199.99 },
|
||||
];
|
||||
|
||||
const totalPrice = calculateTotalPrice(shoppingCart);
|
||||
console.log('Total Price:', totalPrice);
|
||||
|
||||
function displayUserProfile(user) {
|
||||
console.log(`Name: ${user.name}`);
|
||||
console.log(`Age: ${user.age}`);
|
||||
console.log(`Email: ${user.email.toLowerCase()}`);
|
||||
}
|
||||
|
||||
const userProfile = {
|
||||
name: 'Sarah',
|
||||
age: 'twenty-five',
|
||||
email: 'SARAH@EXAMPLE.COM',
|
||||
};
|
||||
|
||||
displayUserProfile(userProfile);
|
||||
|
||||
function getFirstItemName(items) {
|
||||
return items[0].name.toUpperCase();
|
||||
}
|
||||
|
||||
console.log('First Item:', getFirstItemName(shoppingCart)); // => LAPTOP
|
||||
|
||||
const numberList = [1, 2, 3, 4, 5];
|
||||
const sum = numberList.reduce((acc, num) => acc + Number(num), 0);
|
||||
console.log('Sum:', sum); // => 15
|
||||
@@ -0,0 +1,8 @@
|
||||
function calculateAverage(numbers) {
|
||||
const total = numbers.reduce((sum, num) => sum + num, 0);
|
||||
const average = total / numbers.length;
|
||||
return average;
|
||||
}
|
||||
|
||||
console.log(calculateAverage([10, 20, 30])); // => 20
|
||||
console.log(calculateAverage([5, 15, 25, 35])); // => 20
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
// logical error
|
||||
function findMaximum(a, b, c) {
|
||||
if (a > b && a > c) {
|
||||
return a;
|
||||
} else if (b > a && b > c) {
|
||||
return b;
|
||||
} else {
|
||||
return c;
|
||||
}
|
||||
// if (a >= b && a >= c) {
|
||||
// return a;
|
||||
// } else if (b >= a && b >= c) {
|
||||
// return b;
|
||||
// } else {
|
||||
// return c;
|
||||
// }
|
||||
|
||||
return Math.max(a, b, c);
|
||||
}
|
||||
|
||||
console.log(findMaximum(1, 2, 3)); // => 3
|
||||
|
||||
@@ -1,17 +1,45 @@
|
||||
'use strict';
|
||||
|
||||
(() => {
|
||||
// === DOM & VARS =======
|
||||
const DOM = {};
|
||||
// ===== DOM =====
|
||||
const DOM = {
|
||||
temperatureForm: document.querySelector('#temperatureForm'),
|
||||
celsiusInput: document.querySelector('#celsius'),
|
||||
result: document.querySelector('#result'),
|
||||
};
|
||||
|
||||
// === INIT =============
|
||||
const init = () => {};
|
||||
// ===== INIT =====
|
||||
const init = () => {
|
||||
DOM.temperatureForm.addEventListener('submit', handleFormSubmit);
|
||||
};
|
||||
|
||||
// === EVENTHANDLER =====
|
||||
// ===== EVENT HANDLERS =====
|
||||
function handleFormSubmit(e) {
|
||||
e.preventDefault();
|
||||
const celsius = Number(DOM.celsiusInput.value);
|
||||
|
||||
// === XHR/FETCH ========
|
||||
if (isNaN(celsius)) {
|
||||
alert('Please enter a valid number');
|
||||
return;
|
||||
}
|
||||
const fahrenheit = convertToFahrenheit(celsius);
|
||||
|
||||
// === FUNCTIONS ========
|
||||
displayResult(fahrenheit);
|
||||
|
||||
DOM.temperatureForm.reset();
|
||||
}
|
||||
|
||||
// ===== FUNCTIONS =====
|
||||
function convertToFahrenheit(celsius) {
|
||||
if (typeof celsius === 'string') return 0;
|
||||
|
||||
return (celsius * 9) / 5 + 32;
|
||||
}
|
||||
|
||||
function displayResult(result) {
|
||||
DOM.result.textContent = result.toFixed(2);
|
||||
}
|
||||
|
||||
// ===== CALL INIT =====
|
||||
init();
|
||||
})();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!DOCTYPE html>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
@@ -16,7 +16,7 @@
|
||||
<div class="row mb-3 align-items-center">
|
||||
<label for="celsius" class="col-md-3 col-form-label">Celsius:</label>
|
||||
<div class="col-sm-8">
|
||||
<input type="text" id="celsius" name="celsius" class="form-control" required />
|
||||
<input type="number" id="celsius" name="celsius" class="form-control" required />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user