Last active
May 23, 2019 16:32
-
-
Save leofab86/f6927541062e4bf7c343029ea2121c70 to your computer and use it in GitHub Desktop.
Fuzzy search autocomplete v1.2.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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