1
+ const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json' ;
2
+
3
+ const cities = [ ] ;
4
+
5
+ //fetch will return a promise
6
+ fetch ( endpoint )
7
+ // .then(blob => console.log(blob))
8
+ //data that comes back from fetch, it doesn't know what it's coming back yet; blob needs to be converted from raw data into JSON
9
+ . then ( blob => blob . json ( ) )
10
+ . then ( data => cities . push ( ...data ) )
11
+
12
+ function findMatches ( wordToMatch , cities ) {
13
+ return cities . filter ( place => {
14
+ //here we need to figure out if city/state matches what was searched
15
+ const regex = new RegExp ( wordToMatch , 'gi' ) ;
16
+ return place . city . match ( regex ) || place . state . match ( regex )
17
+ } )
18
+ }
19
+
20
+ function numberWithCommas ( x ) {
21
+ return x . toString ( ) . replace ( / \B (? = ( \d { 3 } ) + (? ! \d ) ) / g, ',' ) ;
22
+ }
23
+
24
+ //whenever someone changes the values
25
+ function displayMatches ( ) {
26
+ // console.log(this.value)
27
+ const matchArray = findMatches ( this . value , cities ) ;
28
+ // console.log(matchArray)
29
+ const html = matchArray . map ( place => {
30
+ //find whatever is in regex
31
+ const regex = new RegExp ( this . value , 'gi' )
32
+ const cityName = place . city . replace ( regex , `<span class="hl">${ this . value } </span>` )
33
+ const stateName = place . state . replace ( regex , `<span class="hl">${ this . value } </span>` )
34
+ return `
35
+ <li>
36
+ <span class="name">${ cityName } , ${ stateName } </span>
37
+ <span class="population">${ numberWithCommas ( place . population ) } </span>
38
+ </li>
39
+ ` ;
40
+ } ) . join ( '' ) ;
41
+ suggestions . innerHTML = html ;
42
+ }
43
+
44
+ const searchInput = document . querySelector ( '.search' ) ;
45
+ const suggestions = document . querySelector ( '.suggestions' ) ;
46
+
47
+ searchInput . addEventListener ( 'change' , displayMatches )
48
+ searchInput . addEventListener ( 'keyup' , displayMatches )
0 commit comments