Skip to content

Instantly share code, notes, and snippets.

@leofab86
Last active May 23, 2019 16:46
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/8174f720f123378da1c1f3c4ac28f553 to your computer and use it in GitHub Desktop.
Save leofab86/8174f720f123378da1c1f3c4ac28f553 to your computer and use it in GitHub Desktop.
Fuzzy search automcomplete v1.2.4
//workerArray.js
const ports = {};
let cache = {};
let queue;
function initiatePort (workerName, port) {
ports[workerName] = port;
const webWorker = ports[workerName];
webWorker.inUse = false;
webWorker.onmessage = function handleResults (e) {
const {searchTerm, searchResults} = e.data;
const message = {searchTerm, searchResults};
/* If all workers happen to be inUse, the message gets saved to the
the queue and passed to the first worker that finishes */
if(queue) {
webWorker.postMessage(queue);
webWorker.inUse = true;
queue = null;
} else {
webWorker.inUse = false;
}
cache[searchTerm] = message;
self.postMessage(message);
}
}
function dispatchSearchRequest (searchTerm) {
const cachedResult = cache[searchTerm];
if(cachedResult) {
self.postMessage(cachedResult);
return
}
const message = {searchTerm};
for (const workerName in ports) {
const webWorker = ports[workerName];
if(!webWorker.inUse) {
webWorker.postMessage(message);
webWorker.inUse = true;
return
}
}
queue = message;
}
self.onmessage = function (e) {
const {workerName, searchTerm} = e.data;
if(workerName) {
initiatePort(workerName, e.ports[0]);
} else if(searchTerm) {
dispatchSearchRequest(searchTerm);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment