-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
29 lines (26 loc) · 1018 Bytes
/
main.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
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
const searchInput = document.querySelector('.search');
const suggestionsList = document.querySelector('.suggestions');
fetch(endpoint)
.then(response => response.json())
.then(cityData => {
searchInput.addEventListener('input', () => filterCityData(cityData));
});
function filterCityData(cityData) {
if (!searchInput.value) {
suggestionsList.innerHTML = '<li>Filter for a city</li><li>or a state</li>';
return;
}
const regex = new RegExp(searchInput.value, 'gi');
suggestionsList.innerHTML = cityData
.filter(data => regex.test(data.city) || regex.test(data.state))
.reduce((acc, match) => {
const locationString = `${match.city}, ${match.state}`
.replace(regex, m => `<span class="hl">${m}</span>`);
return acc +=
`<li>
<span>${locationString}</span>
<span class="population">${match.population}</span>
</li>\n`;
}, '');
}