2021-05-21 22:50:40 +03:00
|
|
|
const isPrime = (number) => {
|
|
|
|
if (number % 2 === 0 && number > 2) {
|
2021-07-04 01:48:04 +03:00
|
|
|
return false
|
2021-05-21 22:50:40 +03:00
|
|
|
}
|
|
|
|
|
2021-07-04 01:48:04 +03:00
|
|
|
let start = 2
|
|
|
|
const limit = Math.sqrt(number)
|
2021-05-21 22:50:40 +03:00
|
|
|
while (start <= limit) {
|
|
|
|
if (number % start++ < 1) {
|
2021-07-04 01:48:04 +03:00
|
|
|
return false
|
2021-05-21 22:50:40 +03:00
|
|
|
}
|
|
|
|
}
|
2021-07-04 01:48:04 +03:00
|
|
|
return number > 1
|
|
|
|
}
|
2021-05-21 22:50:40 +03:00
|
|
|
|
2021-07-04 01:48:04 +03:00
|
|
|
addEventListener('message', (e) => {
|
|
|
|
const { startTime } = e.data
|
2021-05-21 22:50:40 +03:00
|
|
|
|
2021-07-04 01:48:04 +03:00
|
|
|
let n = 0
|
|
|
|
let total = 0
|
|
|
|
const THRESHOLD = e.data.value
|
|
|
|
const primes = []
|
2021-05-21 22:50:40 +03:00
|
|
|
|
2021-07-04 01:48:04 +03:00
|
|
|
let previous = startTime
|
2021-05-21 22:50:40 +03:00
|
|
|
|
|
|
|
while (++n <= THRESHOLD) {
|
|
|
|
if (isPrime(n)) {
|
2021-07-04 01:48:04 +03:00
|
|
|
primes.push(n)
|
|
|
|
total++
|
2021-05-21 22:50:40 +03:00
|
|
|
|
2021-07-04 01:48:04 +03:00
|
|
|
const now = Date.now()
|
2021-05-21 22:50:40 +03:00
|
|
|
|
|
|
|
if (now - previous > 250) {
|
2021-07-04 01:48:04 +03:00
|
|
|
previous = now
|
2021-05-21 22:50:40 +03:00
|
|
|
postMessage({
|
2021-07-04 01:48:04 +03:00
|
|
|
status: 'calculating',
|
2021-05-21 22:50:40 +03:00
|
|
|
count: total,
|
2021-07-04 01:48:04 +03:00
|
|
|
time: Date.now() - startTime
|
|
|
|
})
|
2021-05-21 22:50:40 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-04 01:48:04 +03:00
|
|
|
postMessage({ status: 'done', count: total, time: Date.now() - startTime })
|
|
|
|
})
|