|
| 1 | +/** |
| 2 | + * JavaScript30 by Wes Bos, https://javascript30.com/ |
| 3 | + * TypeScript implementation by Will Wager |
| 4 | + * Project: Type Ahead |
| 5 | + * Concepts: AJAX, Fetch API |
| 6 | + * Key takeaways: Get the data first, then worry about displaying it. |
| 7 | + * Sidenotes: |
| 8 | + * Fetch API uses Promises. |
| 9 | + * I've no idea how that comma adding regexp works... |
| 10 | + */ |
| 11 | + |
| 12 | +interface City { |
| 13 | + city: string; |
| 14 | + state: string; |
| 15 | + population: number; |
| 16 | +} |
| 17 | + |
| 18 | +const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; |
| 19 | + |
| 20 | +const cities: City[] = []; |
| 21 | + |
| 22 | +fetch(endpoint) |
| 23 | + .then(blob => blob.json()) |
| 24 | + .then(data => cities.push(...(data as City[]))); |
| 25 | + |
| 26 | +function findMatches(wordToMatch: string, cities: City[]) { |
| 27 | + return cities.filter(place => { |
| 28 | + const regexp = new RegExp(wordToMatch, 'gi'); |
| 29 | + return place.city.match(regexp) || place.state.match(regexp); |
| 30 | + }); |
| 31 | +} |
| 32 | + |
| 33 | +function numberWithCommas(x: number) { |
| 34 | + return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); |
| 35 | +} |
| 36 | + |
| 37 | +function displayMatches() { |
| 38 | + const matchArray = findMatches(this.value, cities); |
| 39 | + const html = matchArray.map(place => { |
| 40 | + const regexp = new RegExp(this.value, 'gi'); |
| 41 | + const cityName = place.city.replace(regexp, `<span class="hl">${this.value}</span>`); |
| 42 | + const stateName = place.state.replace(regexp, `<span class="hl">${this.value}</span>`); |
| 43 | + return (` |
| 44 | + <li> |
| 45 | + <span class="name">${cityName}, ${stateName}</span> |
| 46 | + <span class="population">${numberWithCommas(place.population)}</span> |
| 47 | + </li> |
| 48 | + `); |
| 49 | + }).join(''); |
| 50 | + |
| 51 | + if (suggestions) { |
| 52 | + suggestions.innerHTML = html; |
| 53 | + } else { |
| 54 | + throw new Error('Suggestions block not found'); |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +const searchInput = document.querySelector('.search'); |
| 59 | +const suggestions = document.querySelector('.suggestions'); |
| 60 | + |
| 61 | +if (searchInput) { |
| 62 | + searchInput.addEventListener('change', displayMatches); |
| 63 | + searchInput.addEventListener('keyup', displayMatches); |
| 64 | +} else { |
| 65 | + throw new Error('Search input not found'); |
| 66 | +} |
0 commit comments