-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
91 lines (76 loc) · 2.34 KB
/
script.js
File metadata and controls
91 lines (76 loc) · 2.34 KB
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
const main = document.getElementById("main");
const addUser = document.getElementById("add-user");
const double = document.getElementById("double");
const showMillionare = document.getElementById("millionare");
const sort = document.getElementById("sort");
const total = document.getElementById("culculate-wealth");
getRandomUser();
getRandomUser();
getRandomUser();
let data = [];
//fetch User data from api using aysnc await
async function getRandomUser() {
const res = await fetch("https://randomuser.me/api");
const data = await res.json();
const user = data.results[0];
const newUser = {
pic: `${user.picture.medium}`,
name: `${user.name.first} ${user.name.last}`,
money: Math.floor(Math.random() * 1000000),
};
addData(newUser);
}
//Add new User
function addData(obj) {
data.push(obj);
updateDOM();
}
// Update DOM
function updateDOM() {
main.innerHTML = `<h2><strong>Person</strong> Wealth</h2>`;
data.forEach((item) => {
let element = document.createElement("div");
element.classList.add("person");
element.innerHTML = `<img src="${item.pic}"><strong> ${
item.name
}     </strong> ${formatMoeny(item.money)}`;
main.appendChild(element);
});
}
//format money
function formatMoeny(number) {
return "$" + number.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, "$&,");
}
//Double Money
function doubleMoney() {
data = data.map((item) => {
return { ...item, money: item.money * 2 };
});
updateDOM();
}
//show only Millionare
function showMillionareOnly() {
data = data.filter((user) => user.money > 1000000);
updateDOM();
}
//Sort by richest
function sortByRichest() {
data = data.sort((a, b) => b.money - a.money);
updateDOM();
}
//total wealth
function totalWealth() {
const wealth = data.reduce((acc, user) => (acc += user.money), 0);
const wealthEl = document.createElement("div");
wealthEl.innerHTML = `<h3>Total Wealth: <strong>${formatMoeny(
wealth
)}</strong></h3>`;
updateDOM();
main.appendChild(wealthEl);
}
//Event Listeners
addUser.addEventListener("click", getRandomUser);
double.addEventListener("click", doubleMoney);
showMillionare.addEventListener("click", showMillionareOnly);
sort.addEventListener("click", sortByRichest);
total.addEventListener("click", totalWealth);