-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
88 lines (71 loc) · 2.71 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const generateId = () => `id${Math.round(Math.random() * 1e8).toString(16)}`;
const totalBalance = document.querySelector(".total__balance"),
totalMoneyIncome = document.querySelector(".total__money-income"),
totalMoneyExpenses = document.querySelector(".total__money-expenses"),
historyList = document.querySelector(".history__list"),
form = document.querySelector("#form"),
operationName = document.querySelector(".operation__name"),
operationAmount = document.querySelector(".operation__amount");
let dbOperation = JSON.parse(localStorage.getItem("calc")) || [];
const renderOperation = (operation) => {
const className =
operation.amount < 0 ? "history__item-minus" : "history__item-plus";
const listItem = document.createElement("li");
listItem.classList.add("history__item");
listItem.classList.add(className);
listItem.innerHTML = `${operation.description}
<span class="history__money">${operation.amount}</span>
<button class="history_delete" data-id="${operation.id}">x</button>
`;
historyList.append(listItem);
};
const updateBalance = () => {
const resultIncome = dbOperation
.filter((item) => item.amount > 0)
.reduce((result, item) => result + item.amount, 0);
const resultExpenses = dbOperation
.filter((item) => item.amount < 0)
.reduce((result, item) => result + item.amount, 0);
totalMoneyIncome.textContent = resultIncome + " ₽";
totalMoneyExpenses.textContent = resultExpenses + " ₽";
totalBalance.textContent = resultIncome + resultExpenses + " ₽";
};
const deleteOperation = (event) => {
const target = event.target;
if (target.classList.contains("history_delete")) {
dbOperation = dbOperation.filter(
(operation) => operation.id !== target.dataset.id
);
init();
}
};
const init = () => {
historyList.textContent = "";
dbOperation.forEach(renderOperation);
updateBalance();
localStorage.setItem("calc", JSON.stringify(dbOperation));
};
const addOperation = (event) => {
event.preventDefault();
const operationNameValue = operationName.value,
operationAmountValue = operationAmount.value;
operationName.style.borderColor = "";
operationAmount.style.borderColor = "";
if (operationNameValue && operationAmountValue) {
const operation = {
id: generateId(),
description: operationNameValue,
amount: +operationAmountValue,
};
dbOperation.push(operation);
init();
} else {
if (!operationNameValue) operationName.style.borderColor = "red";
if (!operationAmountValue) operationAmount.style.borderColor = "red";
}
operationName.value = "";
operationAmount.value = "";
};
form.addEventListener("submit", addOperation);
historyList.addEventListener("click", deleteOperation);
init();