|
| 1 | +const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; |
| 2 | + |
| 3 | +const cities = [] |
| 4 | + |
| 5 | +fetch(endpoint) |
| 6 | + .then(response => response.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(regex) |
| 13 | + }) |
| 14 | +} |
| 15 | + |
| 16 | +function numberWithCommas(x) { |
| 17 | + return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); |
| 18 | +} |
| 19 | + |
| 20 | +function displayMatches() { |
| 21 | + const matchArr = findMatches(this.value, cities) |
| 22 | + const regex = new RegExp(this.value, 'gi') |
| 23 | + |
| 24 | + const html = matchArr.map(place => { |
| 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 | + |
| 28 | + return ` |
| 29 | + <li> |
| 30 | + <span class="name">${cityName}, ${stateName}</span> |
| 31 | + <span class="population">${numberWithCommas(place.population)}</span> |
| 32 | + </li> |
| 33 | + ` |
| 34 | + }).join('') |
| 35 | + suggestions.innerHTML = html; |
| 36 | +} |
| 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