Last active
October 8, 2018 09:02
-
-
Save OlivierPerceboisGarve/075c318f129633740f77a562d5014ac9 to your computer and use it in GitHub Desktop.
Duplicates finder
This file contains hidden or 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
<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> |
This file contains hidden or 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
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