1515 </ ul >
1616 </ form >
1717< script >
18- const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json' ;
18+ const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json' ;
19+
20+ const cities = [ ] ;
21+ fetch ( endpoint )
22+ . then ( blob => blob . json ( ) )
23+ . then ( data => cities . push ( ...data ) )
24+
25+ function findMatches ( wordToMatch , cities ) {
26+ return cities . filter ( place => {
27+ //here we need to figure out if the city or state matchings with what was searched
28+ const regex = new RegExp ( wordToMatch , 'gi' )
29+ return place . city . match ( regex ) || place . state . match ( regex )
30+ } )
31+ }
32+
33+ function numberWithCommas ( x ) {
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 regex = new RegExp ( this . value , 'gi' )
41+ const cityName = place . city . replace ( regex , `<span class="hl">${ this . value } </span>` )
42+ const stateName = place . state . replace ( regex , `<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+ suggestions . innerHTML = html
51+ }
52+
53+ const searchInput = document . querySelector ( '.search' )
54+ const suggestions = document . querySelector ( '.suggestions' )
55+
56+ searchInput . addEventListener ( 'change' , displayMatches )
57+ searchInput . addEventListener ( 'keyup' , displayMatches )
1958
2059</ script >
2160 </ body >
2261</ html >
62+
63+ <!-- //fetch returns a promise -->
0 commit comments