Create a gist now

Instantly share code, notes, and snippets.

@totoraj930 /prime.js Secret
Created Jul 11, 2016

Web Workersを利用した素数一覧表示テスト
var worker = createWorker(workerScript);
console.time("prime");
worker.postMessage(1000000);
worker.addEventListener("message", function (event) {
console.timeEnd("prime");
document.querySelector("body").innerHTML = event.data.join(", ");
});
function createWorker(script) {
var re = /^function\s*\w*\s*\([\w\s,]*\)\s*{([\w\W]*?)}$/,
body = script.toString().trim().match(re)[1],
blob = new Blob([body], {type: "text/javascript"}),
url = URL.createObjectURL(blob);
return new Worker(url);
}
function workerScript() {
addEventListener("message", function (event) {
postMessage(prime(event.data));
});
function prime(limit) {
var primes = [];
if (limit < 2) return primes;
primes.push(2);
if (limit <= 2) return primes;
for (var i=3; i <= limit; i++) {
for (var j=0; j < primes.length; j++) {
if (i % primes[j] === 0) break;
if (j+1 >= primes.length) primes.push(i);
}
}
return primes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment