· 4 years ago · Mar 14, 2021, 03:34 PM
1function fetchData(min, max) {
2 fetch('http://www.mocky.io/v2/5d73bf3d3300003733081869')
3 //to check if the response for fetching API is successful or not, if not will throw an error out.
4 .then(response => {
5 if (!response.ok) {
6 throw Error('ERROR');
7 }
8 return response.json();
9 })
10 .then(data => {
11 //doing insertion sort which is a simple algorithm, to sort them from age, youngest to oldest.
12 let key;
13 let j;
14 for(let i =0;i<data.length;i++){
15 key_holder = data[i];
16 key = data[i].age;
17 j = i - 1;
18
19 while(j >= 0 && data[j].age > key){
20 data[j+1] = data[j];
21 j = j-1;
22 }
23 data[j+1] = key_holder;
24 }
25 const html = data
26 //to check what data to show based on age filter given and will show the it on the html.
27 .map(user => {
28 if(user.age >= min && user.age <= max){
29 return `
30 <div class="col-4" style="padding-bottom: 20px">
31 <div class="card card-body">
32 <h5>${user.name}</h5>
33 <img src="img_avatar.jpg" alt="" class="circle" width="100" height="100">
34 <p>Email: ${user.email} <br>
35 Mobile: ${user.phone} <br>
36 Company: ${user.company} <br>
37 Address: ${user.address.street} <br>
38 Website: ${user.website} <br>
39 Age: ${user.age}</p>
40 </div>
41 </div>
42 `;
43 }
44 })
45 .join("");
46 console.log(html);
47 document.querySelector("#app").insertAdjacentHTML("afterbegin", html);
48 });
49}
50
51// this code will help to see if user had made a selection and change data accordingly but only after clicking outside of the dropdown box.
52document.onselectionchange = function() {
53 document.querySelector("#app").innerHTML = "";
54 let min, max;
55 let filter = document.querySelector("#age").value;
56 console.log(filter);
57 switch(filter){
58 case "all":
59 min = 0;
60 max = 200;
61 break;
62 case "below20":
63 min = 0;
64 max = 21;
65 break;
66 case "21above":
67 min = 21;
68 max = 39;
69 break;
70 case "40andabove":
71 min = 40;
72 max = 200;
73 break;
74 default:
75 min = 0;
76 max = 200;
77 break;
78 }
79 fetchData(min, max);
80};