Skip to content

Instantly share code, notes, and snippets.

@leofab86 leofab86/webWorker.js
Last active May 23, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.