Skip to content

Instantly share code, notes, and snippets.

@WillMayger
Last active November 7, 2019 23:00
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 WillMayger/75cd40c975d32356a21bb04ee1a6ea20 to your computer and use it in GitHub Desktop.
Save WillMayger/75cd40c975d32356a21bb04ee1a6ea20 to your computer and use it in GitHub Desktop.
worker searching using divide and conquer
// Uses divide and conquer to find the location of a range of date times within a large array of datetimes.
// It then uses this location to match the date on another array of the same order containing more information about the date.
/* eslint-disable */
const worker = () => {
function divideAndConquer(lookFor, data, len, order) {
const half = Math.floor(len - 1 / 2);
if (!data[half]) return -1;
if (data[half] === lookFor) return half;
if (order === 'A' && data[half] < lookFor) {
return divideAndConquer(lookFor, data.slice(half, half * 2), half, order);
} else if (order === 'D' && data[half] < lookFor) {
return divideAndConquer(lookFor, data.slice(0, half), half, order);
}
if (order === 'A' && data[half] > lookFor) {
return divideAndConquer(lookFor, data.slice(0, half), half, order);
} else if (order === 'D' && data[half] > lookFor) {
return divideAndConquer(lookFor, data.slice(half, half * 2), half, order);
}
return -1;
}
self.addEventListener('message', function(e) {
const {
len,
dates,
dateTimes,
metrics,
start,
end,
} = e.data;
const from = divideAndConquer(start, dateTimes, dateTimes.length, 'D');
const to = divideAndConquer(end, dateTimes, dateTimes.length, 'D');
const data = {
dates: dates.slice(from, to).reverse(),
metrics: metrics.slice(from, to).reverse(),
};
self.postMessage(data);
}, false);
}
let code = worker.toString();
code = code.substring(code.indexOf("{")+1, code.lastIndexOf("}"));
const blob = new Blob([code], {type: "application/javascript"});
const workerScript = URL.createObjectURL(blob);
export {
workerScript
}
@WillMayger
Copy link
Author

Uses divide and conquer to find the location of a range of date times within a large array of datetimes.
It then uses this location to match the date on another array of the same order containing more information about the date.
Finally it also converts the code into a blob that can be accessed relatively from another file (this is useful when code gets minified into fewer files and to start a web worker you need a separated file)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment