-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
103 lines (81 loc) · 2.49 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
const main = document.getElementById('main');
const addUserBtn = document.getElementById('add-user');
const doubleBtn = document.getElementById('double');
const showMillionBtn = document.getElementById('show-millionaires');
const sortBtn = document.getElementById('sort');
const calWealthBtn = document.getElementById('calculate-wealth');
let data = [];
let tempData = 0;
getRandomUser();
getRandomUser();
getRandomUser();
/*
Fetching User and adding Money
*/
async function getRandomUser() {
const res = await fetch('https://randomuser.me/api');
const reData = await res.json();
let user = reData.results[0];
const newUser = {
name: `${user.name.first} ${user.name.last}`,
money: Math.floor(Math.random() * 10000000)
};
console.log(newUser);
addData(newUser);
}
//Double Everyone Money
function doubleMoney() {
data = data.map(user => {
return { ...user, money: user.money * 2 }
})
updateDOM();
}
//Sort User by Richest
function sortByRichest() {
data.sort((a, b) => b.money - a.money);
updateDOM();
}
//Show Millonaries
function showMillionaries() {
data = data.filter(user => user.money >= 1000000);
updateDOM();
}
//Calculate Total Wealth
function calculateWealth() {
let wealth = data.reduce((acc, user) => (acc += user.money), 0);
if (tempData != wealth) {
tempData = wealth;
const wealthEl = document.createElement('div');
wealthEl.innerHTML = `<h3>Total Wealth: <strong>${formatMoney(wealth)}</strong></h3>`;
main.appendChild(wealthEl);
}
}
//Add new User in Data
function addData(obj) {
data.push(obj);
updateDOM()
}
//Updating dom
function updateDOM(providedData = data) {
//clearing existing data in HTML
main.innerHTML = `<h2><strong>Person</strong> Wealth</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);
})
}
//Formating Number as Money
function formatMoney(number) {
return '$' + number.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}
//Event Listeners
addUserBtn.addEventListener('click', getRandomUser);
doubleBtn.addEventListener('click', doubleMoney);
sortBtn.addEventListener('click', sortByRichest);
showMillionBtn.addEventListener('click', showMillionaries);
calWealthBtn.addEventListener('click', calculateWealth);