Skip to content

Instantly share code, notes, and snippets.

@OlivierPerceboisGarve
Last active October 8, 2018 09:02
Show Gist options
  • Save OlivierPerceboisGarve/075c318f129633740f77a562d5014ac9 to your computer and use it in GitHub Desktop.
Save OlivierPerceboisGarve/075c318f129633740f77a562d5014ac9 to your computer and use it in GitHub Desktop.
Duplicates finder
<script type="text/js-worker">
const getRandomInt = (max) => Math.floor(Math.random() * (max + 1));
const findDuplicates = (e) => {
const ints = [], dupes = [], n = e.data;
for(let i = 0; i <= n; i++){
let randomInt = getRandomInt(n);
if (ints.includes(randomInt) && !dupes.includes(randomInt)){
dupes.push(randomInt);
}
ints.push(randomInt);
if (i%100==0 || i==n){
self.postMessage({i: i, dupes: dupes});
}
}
}
self.addEventListener('message', (e) => findDuplicates(e));
</script>
<input type="number" id="intsRange" step="1" min="1" max="5000000" value="1000000"/>
<button type="button" id="toggleStartStop">Start</button>
<div id="output"></div>
const findDuplicates = function(inputElement,outputElement) {
let worker = undefined;
const createWorker = () => {
const blob = new Blob(
Array.prototype.map.call(
document.querySelectorAll('script[type="text\/js-worker"]'),
(oScript) => oScript.textContent
),
{ type: 'text/javascript' }
);
return new Worker(window.URL.createObjectURL(blob));
}
const startWorker = () => {
if(worker === undefined){
worker = createWorker();
worker.addEventListener('message', (e) => {
let out = `Processed ${e.data.i}. ${e.data.dupes.length} duplicates : ${e.data.dupes.join(' ')}`;
outputElement.innerHTML = out;
});
worker.postMessage(inputElement.value);
}
}
const stopWorker = () =>{
if (worker && worker.terminate){
worker.terminate();
}
worker = undefined;
}
const isRunning = () => {
return (worker) ? true: false;
}
return {startWorker,stopWorker, isRunning};
}
const fd = new findDuplicates(document.getElementById('intsRange'), document.getElementById('output'));
document.getElementById('toggleStartStop').addEventListener('click', (e) => {
if (!fd.isRunning()){
fd.startWorker();
e.target.innerHTML='Stop';
} else {
fd.stopWorker();
e.target.innerHTML='Restart';
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment