Primecheck function is supposed to return true or false whether passed number is prime or not. If the number is prime, function adds it to PRIMES table. This is a Sieve of Eratosthenes algorithm, but it's not finished yet.
function primecheck (number) {
var isprime = true;
if (number%10 == 1 || number%10 == 3 || number%10 == 7 || number%10 == 9) {
db.transaction(function (tx) {
tx.executeSql('SELECT * from Primes', [], function (tx, result) {
for (var i = 1; i < result.rows.length; i++) {
if (number%result.rows.item(i)['prime'] == 0) {
isprime = false;
break;
}
}
if (isprime) {
tx.executeSql('INSERT INTO PRIMES (prime) values (?)', [number]);
}
return isprime;
}, null);
}, null, null);
}
else {
isprime = false;
return isprime;
}
}
Problem: when I pass numbers that do not end on 1, 3, 7, 9, function returns true, it's ok. But when I pass other numbers, function returns undefined. I suppose it's because function call doesn't "wait" for SQL query to finish, so I must use some kind of callback functions. But it didn't work.
primecheck
, and executecallback(isprime)
instead ofreturn isprime
. (Also, you don't need to select primes which are larger thansqrt(number)
). – Eigenvalue