Skip to content

Instantly share code, notes, and snippets.

@leofab86
Last active May 23, 2019 18:08
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/df4bf9c697a95c800f40c38a2478ed2d to your computer and use it in GitHub Desktop.
Save leofab86/df4bf9c697a95c800f40c38a2478ed2d 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 = {}
//thought I would add a simple cache... Wait till you see those deletes now :)
function initiateSearchEngine (data) {
//initiate the search engine with the 13,000 item data set
searchEngine = new SearchEngine(data);
//reset the cache on initiate just in case
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 is the api for sending messages to main thread
self.postMessage(message)
}
/*self.onmessage is where we define the handler for messages recieved
from the main thread*/
self.onmessage = function(e) {
const {data, searchTerm} = e.data;
/*We can determine how to respond to the .postMessage from
SearchResults.js based on which data properties it has:*/
if(data) {
initiateSearchEngine(data)
} else if(searchTerm) {
search(searchTerm)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment