Skip to content

Commit 1999cf5

Browse files
committed
Day 6: Add a functional type ahead
This one blew my mind. It seems like such a complicated feature but Wes made it feel easy. I love that he found the same regex that I used in my data project and I'm likely going to be able to use this in there to sort tracks
1 parent 8bf46eb commit 1999cf5

1 file changed

Lines changed: 31 additions & 2 deletions

File tree

06 - Type Ahead/day-06.js

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,34 @@ fetch(endpoint)
1313
.then(blob => blob.json())
1414
.then(data => cities.push(...data))
1515

16-
console.clear();
17-
console.log(cities);
16+
function findMatches(wordToMatch, cities) {
17+
return cities.filter(place => {
18+
const regex = new RegExp(wordToMatch, 'gi');
19+
return place.city.match(regex) || place.state.match(regex);
20+
});
21+
}
22+
23+
function numberWithCommas(x) {
24+
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
25+
}
26+
27+
function displayMatches() {
28+
const matchArray = findMatches(this.value, cities);
29+
const html = matchArray.map(place => {
30+
const regex = new RegExp(this.value, 'gi');
31+
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
32+
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
33+
return `
34+
<li>
35+
<span class='name'>${cityName}, ${stateName}</span>
36+
<span class='population'>${numberWithCommas(place.population)}</span>
37+
</li>
38+
`;
39+
}).join('');
40+
suggestions.innerHTML = html;
41+
}
42+
43+
const searchInput = document.querySelector('.search');
44+
const suggestions = document.querySelector('.suggestions');
45+
46+
searchInput.addEventListener('input', displayMatches);

0 commit comments

Comments
 (0)