-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
executable file
·111 lines (88 loc) · 2.6 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
const main = document.getElementById('main');
const addUserBtn = document.getElementById('add-user');
const doubleBtn = document.getElementById('double');
const showMillionairesBtn = document.getElementById('show-millionaires');
const sortBtn = document.getElementById('sort');
const sortByNameBtn = document.getElementById('sort-name');
const calculateWealthBtn = document.getElementById('calculate-wealth');
let data = [];
getRandomUser();
getRandomUser();
getRandomUser();
// Fetch random user and add money
async function getRandomUser() {
const res = await fetch('https://randomuser.me/api');
const data = await res.json();
const user = data.results[0];
const newUser = {
name: `${user.name.first} ${user.name.last}`,
money: Math.floor(Math.random() * 1000000)
};
addData(newUser);
}
// Double eveyones money
function doubleMoney() {
data = data.map(user => {
return { ...user, money: user.money * 2 };
});
updateDOM();
}
// Sort users by richest
function sortByRichest() {
data.sort((a, b) => b.money - a.money);
updateDOM();
}
// Sort users by name
function sortByName() {
data.sort((a, b) => {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
});
updateDOM();
}
// Filter only millionaires
function showMillionaires() {
data = data.filter(user => user.money > 1000000);
updateDOM();
}
// Calculate the total wealth
function calculateWealth() {
const wealth = data.reduce((acc, user) => (acc += user.money), 0);
const wealthEl = document.createElement('div');
wealthEl.innerHTML = `<h3>Riqueza total: <strong>${formatMoney(
wealth
)}</strong></h3>`;
main.appendChild(wealthEl);
}
// Add new obj to data arr
function addData(obj) {
data.push(obj);
updateDOM();
}
// Update DOM
function updateDOM(providedData = data) {
// Clear main div
main.innerHTML = '<h2><strong>Pessoa</strong> Riqueza</h2>';
providedData.forEach(item => {
const element = document.createElement('div');
element.classList.add('person');
element.innerHTML = `<strong>${item.name}</strong> ${formatMoney(
item.money
)}`;
main.appendChild(element);
});
}
function formatMoney(number) {
return number.toLocaleString('pt-br',{style: 'currency', currency: 'BRL'});
}
// Event listeners
addUserBtn.addEventListener('click', getRandomUser);
doubleBtn.addEventListener('click', doubleMoney);
sortBtn.addEventListener('click', sortByRichest);
sortByNameBtn.addEventListener('click', sortByName);
showMillionairesBtn.addEventListener('click', showMillionaires);
calculateWealthBtn.addEventListener('click', calculateWealth);