Skip to content

Commit d288fd7

Browse files
committed
Finished day 6
1 parent b29967d commit d288fd7

File tree

3 files changed

+44
-64
lines changed

3 files changed

+44
-64
lines changed

06 - Type Ahead/index-FINISHED.html

Lines changed: 0 additions & 61 deletions
This file was deleted.

06 - Type Ahead/index-START.html renamed to 06 - Type Ahead/index.html

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,7 @@
1414
<li>or a state</li>
1515
</ul>
1616
</form>
17-
<script>
18-
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
19-
17+
<script src="type.js">
2018
</script>
2119
</body>
2220
</html>

06 - Type Ahead/type.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
2+
3+
const cities = [];
4+
5+
fetch(endpoint)
6+
.then(blob => blob.json())
7+
.then(data => cities.push(...data));
8+
9+
function findMatches(wordToMatch, cities) {
10+
return cities.filter(place => {
11+
const regex = new RegExp(wordToMatch, 'gi');
12+
return place.city.match(regex) || place.state.match(RegExp);
13+
})
14+
}
15+
16+
function numberWithCommas(number) {
17+
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
18+
}
19+
20+
function displayMatches () {
21+
const matchArray = findMatches(this.value, cities);
22+
const html = matchArray.map(place => {
23+
const regex = new RegExp(this.value, 'gi');
24+
25+
const cityName = place.city.replace(regex, `<span class=\"hl\">${this.value}</span>`)
26+
const stateName = place.state.replace(regex, `<span class=\"hl\">${this.value}</span>`)
27+
const population = numberWithCommas(place.population)
28+
29+
return `
30+
<li>
31+
<span class="name">${cityName}, ${stateName}</span>
32+
<spam class="population">${population}</span>
33+
</li>
34+
`;
35+
}).join('');
36+
suggestions.innerHTML = html;
37+
}
38+
39+
const searchInput = document.querySelector('.search');
40+
const suggestions = document.querySelector('.suggestions');
41+
42+
searchInput.addEventListener('change', displayMatches);
43+
searchInput.addEventListener('keyup', displayMatches);

0 commit comments

Comments
 (0)