Skip to content

Instantly share code, notes, and snippets.

@leofab86
Last active May 23, 2019 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leofab86/f6927541062e4bf7c343029ea2121c70 to your computer and use it in GitHub Desktop.
Save leofab86/f6927541062e4bf7c343029ea2121c70 to your computer and use it in GitHub Desktop.
Fuzzy search autocomplete v1.2.2
//webWorker.js
self.importScripts('...the search engine script, provides the SearchEngine constructor');
let searchEngine;
let cache = {}
function initiateSearchEngine (data) {
searchEngine = new SearchEngine(data);
cache = {};
}
function search (searchTerm) {
const cachedResult = cache[searchTerm]
if(cachedResult) {
self.postMessage(cachedResult)
return
}
const message = {
searchResults: searchEngine.search(searchTerm)
};
cache[searchTerm] = message;
self.postMessage(message)
}
function confirmSearchTerm (searchTerm) {
self.postMessage({confirmSearchTerm: searchTerm})
}
self.onmessage = function(e) {
const {data, searchTerm, confirmed} = e.data;
if(data) {
initiateSearchEngine(data)
} else if(searchTerm) {
/*check if the searchTerm is confirmed, if not, send a confirmSearchTerm message
to compare the searchTerm with the latest value on the main thread */
confirmed ? search(searchTerm) : confirmSearchTerm(searchTerm)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment