|
18 | 18 | <script> |
19 | 19 | const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; |
20 | 20 | let cities = [] |
| 21 | + const input = document.querySelector('input') |
| 22 | + const resultsList = document.querySelector('ul') |
| 23 | + |
| 24 | + function onKeypress (e) { |
| 25 | + const search = `${e.target.value}${e.key}` |
| 26 | + const results = find(search, cities) |
| 27 | + console.log('results', results) |
| 28 | + const items = results.reduce((acc, item) => acc = `${acc}<li>${item.state} - ${item.city}</li>`, '') |
| 29 | + resultsList.innerHTML = items |
| 30 | + } |
| 31 | + |
| 32 | + function find (word, cities) { |
| 33 | + const regex = new RegExp(word, 'gi') |
| 34 | + return cities.filter(place => place.state.match(regex) || |
| 35 | + place.city.match(regex)) |
| 36 | + } |
| 37 | + |
| 38 | + function numberWithCommas(x) { |
| 39 | + return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); |
| 40 | + } |
| 41 | + |
| 42 | + function updateList () { |
| 43 | + const results = find(this.value, cities) |
| 44 | + const regex = new RegExp(this.value, 'gi') |
| 45 | + const items = results.reduce((acc, item) => { |
| 46 | + const stateName = item.state.replace(regex, `<span class="hl">${this.value}</span>`) |
| 47 | + const cityName = item.city.replace(regex, `<span class="hl">${this.value}</span>`) |
| 48 | + acc = `${acc}<li> |
| 49 | + <span class"name">${stateName} - ${cityName}</span> |
| 50 | + <span class="population">${numberWithCommas(item.population)}</span> |
| 51 | + </li>` |
| 52 | + return acc |
| 53 | + }, '') |
| 54 | + resultsList.innerHTML = items |
| 55 | + } |
| 56 | + |
| 57 | + input.addEventListener('change', updateList) |
| 58 | + input.addEventListener('keyup', updateList) |
| 59 | + |
21 | 60 | fetch(endpoint) |
22 | 61 | .then(response => response.json()) |
23 | 62 | .then(json => cities = json) |
|
0 commit comments