Zadanie domowe nr 4: Zarządzanie listą produktów
● funkcja dodająca nowy przedmiot do tablicy ● funkcja pokazująca przedmioty z danej kategorii ● funkcja kalkulująca nową cenę przedmiotu ● funkcja modyfikująca przedmiot ● funkcja usuwająca przedmiot ● funkcja sortująca przedmioty alfabetyczni
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stan sklepu</title>
<style>
table { border-collapse: collapse; width: 80%; margin-top: 20px; }
th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
button { margin-top: 10px; padding: 5px 10px; }
</style>
</head>
<body>
<h2>Lista produktów</h2>
<!-- przycisk do odświeżania listy -->
<button onclick="renderList()">Odśwież listę</button>
<div style="margin-bottom: 20px;">
<br>
<label>Sortuj według:</label>
<select id="sortSelect">
<option value="id">ID (domyślnie)</option>
<option value="name">Nazwa (A-Z)</option>
<option value="price">Cena (od najniższej)</option>
<option value="category">Kategoria (A-Z)</option>
</select>
</div>
<!-- tabela produktów -->
<table id="productsTable">
<thead>
<tr>
<th>ID</th>
<th>Nazwa</th>
<th>Kategoria</th>
<th>Cena</th>
<th>Cena z rabatem</th>
</tr>
</thead>
<tbody>
<!-- Produkty będą dodawane dynamicznie przez JS -->
</tbody>
</table>
<form id="addProductForm">
<input type="text" name="name" placeholder="Nazwa produktu" required>
<select name="category" required>
<option value="">-- wybierz kategorię --</option>
<option value="earrings">Earrings</option>
<option value="necklaces">Necklaces</option>
<option value="clothes">Clothes</option>
<option value="other">Other</option>
</select>
<input type="number" name="price" placeholder="Cena" step="0.01" required>
<input type="checkbox" name="promoSale"> Na wyprzedaży
<input type="number" name="promoOff" placeholder="Rabat (%)" step="1" min="0" max="100">
<button type="submit">Dodaj produkt</button>
</form>
<script>
// Baza produktów
let items = []; // początkowo pusta tablica produktów
let nextId = 1; // licznik globalny ID, zaczyna od 1
// FUNKCJE
// 1. Dodawanie produktu
function addItem({ name, category, price, promoSale = false, promoOff = 0 }) {
const newItem = {
id: nextId++, // pobiera aktualny ID, potem zwiększa licznik
name,
category,
price,
promoSale,
promoOff
};
items.push(newItem);
renderList();
return newItem;
}
const form = document.getElementById("addProductForm");
form.addEventListener("submit", function(e) {
e.preventDefault(); // zapobiega przeładowaniu strony.
const formData = new FormData(form);
const name = formData.get("name");
const category = formData.get("category");
const price = Number(formData.get("price"));
const promoSale = formData.get("promoSale") === "on";
const promoOff = Number(formData.get("promoOff")) / 100; // konwersja rabatu na ułamek
addItem({ name, category, price, promoSale, promoOff });
form.reset(); // czyścimy formularz
});
// 2. Filtrowanie
function getItemsByCategory(category) {
return items.filter(item => item.category === category);
}
// 3. Liczenie ceny promocyjnej
function calculatePromoPrice(itemId) {
const item = items.find(item => item.id === itemId);
if (!item) return "Brak produktu";
const newPrice = item.promoSale ? item.price - item.price * item.promoOff : item.price;
return { ...item, newPrice };
}
// MODYFIKACJA (updateItem)
function updateItem(id, updates = {}) {
// Sprawdź czy item istnieje
const existing = items.find(item => item.id === id);
if (!existing) {
console.warn(`Nie znaleziono produktu o id=${id}`);
return null;
}
// Walidacja / konwersje jeżeli potrzebne:
if (updates.price !== undefined) updates.price = Number(updates.price);
if (updates.promoOff !== undefined) updates.promoOff = Number(updates.promoOff);
if (updates.promoSale !== undefined) updates.promoSale = Boolean(updates.promoSale);
// Zastąp obiekt nowym, scalając pola
items = items.map(item =>
item.id === id ? { ...item, ...updates } : item
);
const updated = items.find(el => el.id === id);
console.log(`Zaktualizowano produkt id=${id}:`);
console.table([updated]);
return updated;
}
// USUWANIE (deleteItem)
// Ustawia items = items.filter(...) żeby usunąć produkt.
function deleteItem(id) {
const existing = items.find(item => item.id === id);
if (!existing) {
console.warn(`Nie znaleziono produktu o id=${id}.`);
return null;
}
// Usuń i zwróć usunięty element
items = items.filter(item => item.id !== id);
console.log(`Usunięto produkt id=${id}:`);
console.table([existing]);
return existing;
}
// 3) SORTOWANIE ALFABETYCZNE (sortItems)
function sortItems() {
items.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));
console.log("Posortowano produkty alfabetycznie po nazwie:");
console.table(items);
return items;
}
// 3) SORTOWANIE TABLICY (wg. kategori)
function sortItems(criteria) {
switch (criteria) {
case "name":
items.sort((a, b) => a.name.localeCompare(b.name));
break;
case "price":
items.sort((a, b) => a.price - b.price);
break;
case "category":
items.sort((a,b) => a.category.localeCompare(b.category));
break;
default:
items.sort((a, b) => a.id - b.id); // domyślnie po ID
}
renderList(); // odśwież tabelę po zmianach
}
function renderList() {
const tbody = document.querySelector("#productsTable tbody");
tbody.innerHTML = ""; // czyścimy tabelę
items.forEach(item => {
const promoPrice = item.promoSale
? (item.price - item.price * item.promoOff).toFixed(2)
: item.price.toFixed(2);
//Cena promocyjna obliczana jest dynamicznie: price - price * promoOff.
const row = document.createElement("tr");
row.innerHTML = `
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.category}</td>
<td>${item.price.toFixed(2)}</td>
<td>${promoPrice}</td>
`;
tbody.appendChild(row);
});
}
// Dodanie PRODUKTU BEZPOŚREDNIO W KODZIE
addItem({
name: "Kolczyki Płonące serce",
category: "earrings",
price: 21,
promoSale: true,
promoOff: 0.30
});
addItem({
name: "Kolczyki Kocie spojrzenie",
category: "earrings",
price: 19,
promoSale: true,
promoOff: 0.30
});
addItem({
name: "Kolczyki Ametystowa moc",
category: "earrings",
price: 31,
promoSale: false,
promoOff: 0
});
addItem({
name: "Naszyjnik Miecz w dłoni",
category: "necklaces",
price: 29,
promoSale: false,
promoOff: 0
});
addItem({
name: "Naszyjnik Zew wilka",
category: "necklaces",
price: 26,
promoSale: false,
promoOff: 0
});
renderList();
const sortSelect = document.getElementById("sortSelect");
sortSelect.addEventListener("change", () => {
const selected = sortSelect.value;
sortItems(selected);
});
// WYŚWIETLANIE WYNIKÓW
console.log("Aktualna lista produktów:");
console.table(items);
console.log("Produkty w kategorii 'clothes':");
console.table(getItemsByCategory("clothes"));
// ---------- TESTY ----------
// 1) Dodajemy produkt w kodzie (przykład)
addItem({ name: "Dodanie nowego produktu", category: "clothes", price: 220, promoSale: true, promoOff: 0.5 });
console.log("Po dodaniu:");
console.table(items);
// 2) Modyfikacja: zmieniamy cenę i nazwę itemu o id=3
updateItem(4, { price: 99, name: "Przykład zmiany" });
// 3) Usuwanie: usuwamy item o id=2
deleteItem(2);
renderList();
// 4) Sortowanie: sortujemy alfabetycznie
sortItems();
renderList();
// 5) Pokazanie ceny promocyjnej dla id=1
console.log("Cena promocyjna (id=1):", calculatePromoPrice(1));
</script>
</body>
</html>