|
| 1 | +const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; |
| 2 | + |
| 3 | +const cities = []; |
| 4 | + |
| 5 | +fetch(endpoint) |
| 6 | + .then(blob => blob.json()) |
| 7 | + .then(data => cities.push(...data)); |
| 8 | + |
| 9 | +function findMatches(wordToMatch, cities) { |
| 10 | + return cities.filter(place => { |
| 11 | + const regex = new RegExp(wordToMatch, 'gi'); |
| 12 | + return place.city.match(regex) || place.state.match(RegExp); |
| 13 | + }) |
| 14 | +} |
| 15 | + |
| 16 | +function numberWithCommas(number) { |
| 17 | + return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); |
| 18 | +} |
| 19 | + |
| 20 | +function displayMatches () { |
| 21 | + const matchArray = findMatches(this.value, cities); |
| 22 | + const html = matchArray.map(place => { |
| 23 | + const regex = new RegExp(this.value, 'gi'); |
| 24 | + |
| 25 | + const cityName = place.city.replace(regex, `<span class=\"hl\">${this.value}</span>`) |
| 26 | + const stateName = place.state.replace(regex, `<span class=\"hl\">${this.value}</span>`) |
| 27 | + const population = numberWithCommas(place.population) |
| 28 | + |
| 29 | + return ` |
| 30 | + <li> |
| 31 | + <span class="name">${cityName}, ${stateName}</span> |
| 32 | + <spam class="population">${population}</span> |
| 33 | + </li> |
| 34 | + `; |
| 35 | + }).join(''); |
| 36 | + suggestions.innerHTML = html; |
| 37 | +} |
| 38 | + |
| 39 | +const searchInput = document.querySelector('.search'); |
| 40 | +const suggestions = document.querySelector('.suggestions'); |
| 41 | + |
| 42 | +searchInput.addEventListener('change', displayMatches); |
| 43 | +searchInput.addEventListener('keyup', displayMatches); |
0 commit comments