Last active
May 23, 2019 16:46
-
-
Save leofab86/8174f720f123378da1c1f3c4ac28f553 to your computer and use it in GitHub Desktop.
Fuzzy search automcomplete v1.2.4
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
//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