|
17 | 17 | <script>
|
18 | 18 | const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
|
19 | 19 |
|
| 20 | +const cities = []; |
| 21 | +// fetch will return a promise |
| 22 | +fetch(endpoint) |
| 23 | + .then(blob => blob.json()) |
| 24 | + .then(data => cities.push(...data)); |
| 25 | + |
| 26 | +function findMatches(wordToMatch, cities) { |
| 27 | + return cities.filter(place => { |
| 28 | + // here we need to figure out if the city or state matches what was searched globally and case insensitive |
| 29 | + const regex = new RegExp(wordToMatch, 'gi'); |
| 30 | + return place.city.match(regex) || place.state.match(regex); |
| 31 | + }); |
| 32 | +} |
| 33 | + |
| 34 | +function numberWithCommas(x) { |
| 35 | + return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); |
| 36 | +} |
| 37 | +function displayMatches() { |
| 38 | + const matchArray = findMatches(this.value, cities); |
| 39 | + console.log(matchArray); |
| 40 | + const html = matchArray.map(place => { |
| 41 | + const regex = new RegExp(this.value, 'gi'); |
| 42 | + const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`); |
| 43 | + const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`); |
| 44 | + |
| 45 | + return ` |
| 46 | + <li> |
| 47 | + <span class="name">${place.city}, ${place.state}</span> |
| 48 | + <span class='population'>${numberWithCommas(place.population)}</span> |
| 49 | + </li>` |
| 50 | + }).join(''); |
| 51 | + suggestions.innerHTML = html; |
| 52 | +} |
| 53 | +const searchInput = document.querySelector('.search'); |
| 54 | +const suggestions = document.querySelector('.suggestions'); |
| 55 | + |
| 56 | +searchInput.addEventListener('change', displayMatches); |
| 57 | + |
20 | 58 | </script>
|
21 | 59 | </body>
|
22 | 60 | </html>
|
0 commit comments