JSFiddle - React, Tailwind, and code Playground
HTML
<link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/prampcontent/3ea04cbd0f61a798e96afbe5d31ec2f9/raw/e879e32222b543b29a168daa089e2f9f28cf9eb2/autocomplete.css">
<form class="search-form">
<input type="text" class="search-input" placeholder="Start typing a movie title..." list="results">
<ul class="results"></ul>
</form>
<script src="https://cdn.rawgit.com/prampcontent/180077452f9279073cab1035f60d30cf/raw/9cbf891a80bad9ad09c6261ef9578a65502922cc/search_helper.js"></script>
JavaScript
// Adding this right before the handleChange method
function memoize(func) {
const cache = new Map();
return function(...args) {
// Use first argument as key
const key = args[0];
if (cache.has(key)) {
console.log('cache hit');
return cache.get(key);
}
console.log('cache miss');
const val = func.apply(this, arguments);
cache.set(key, val);
return val;
};
}
// Apply the memoization to the search results method
showSearchResults = memoize(showSearchResults);
// Adding this right after applying memoization
function debounce(fn, time) {
let timeout;
return function() {
const functionCall = () => {
console.log('calling');
return fn.apply(this, arguments);
};
clearTimeout(timeout);
timeout = setTimeout(functionCall, time);
}
}
// Apply the debouncing to the search results method
showSearchResults = debounce(showSearchResults, 200);
function showSearchResults(searchQuery) {
const regex = new RegExp(searchQuery, 'gi');
searchData(searchQuery).then(results => {
const html = results.map(movie => {
const title = movie.title.replace(regex, `<span class="query-highlight">${searchQuery}</span>`);
return `
<li>
<span class="title">${title}</span>
<span class="rating">${movie.rating}</span>
</li>
`;
});
resultsElement.innerHTML = html.join('');
});
}
// Get HTML elements
const searchInputElement = document.querySelector('.search-input');
const resultsElement = document.querySelector('.results');
// Pass
function handleChange() {
return showSearchResults(this.value);
}
// Register for both events
...