Javascript : How can I add X elements to an array - javascript

I need to create an array including the first 100 prime numbers, here is my code:
var premier= [];
var nombre= premier.length;
function isPrime(n)
{
if(n < 2)
{
return false;
}
for(i=2; i<Math.sqrt(n); i++)
{
if(n%i===0)
{
return false;
}
}
return true
};
while(nombre<100)
{
var j=2
if(isPrime(j)==true)
{
premier.push(j);
}
j=j+1
}
I am a beginner in Javascript, but I have tested the isPrime function and it works fine even forlarge numbers.
but when I run the program I have:
FATAL ERROR: JS Allocation failed - process out of memory
I think this part is wrong:
while(nombre<100)
{
var j=2
if(isPrime(j)=true)
{
premier.push(j);
}
j=j+1
}
console.log(premier)
But I can't tell why

You are repeatedly setting j=2 every time the loop runs, and you never change nombre so the loop will never end. Note that JavaScript sets literal vaues by value, not by reference, so nombre = premier.length won't magically update.
Additionally, statements of the form if( x = true) will set x to true, and then pass the condition automatically. In this case, since x is a function call, it is invalid syntax.
Did you mean this?
var j = 2;
while(premier.length < 100) {
if( isPrime(j)) premier.push(j);
j++;
}

Related

Where do I place my return true statement

This is a basic javascript question I just want to better understand. I'm trying to understand if it matters where I place my return true statement. Here's the example code:
function isValid(input) {
for (var i = 0; i < input.length - 2; i++) {
var charOne = input.charAt(i);
var charTwo = input.charAt(i + 1);
var charThree = input.charAt(i + 2);
if (charOne === charTwo && charOne === charThree) {
return false;
}
return true;
}
}
isValid("ABB");
This returns true, but also returns true if I place the return true statement here:
function isValid(input) {
for (var i = 0; i < input.length - 2; i++) {
var charOne = input.charAt(i);
var charTwo = input.charAt(i + 1);
var charThree = input.charAt(i + 2);
if (charOne === charTwo && charOne === charThree) {
return false;
}
}
return true; // Moved this return statement
}
isValid("ABB");
Is one way wrong and the other correct?
Your first version, you are returning true within the for loop. That means its only going to execute your loop once and then return. That's likely a bug.
Your second version is likely correct. The return true statement executes from the function after the for-loop completes all iterations from [i..length-2).
second one, since in the first one after each iteration , you check if characters are equal and it will return false or return true in the first iteration itself.In, second one you check for all combinations and if it's never false then it must be true.
When you return inside a for loop you finish the whole loop and carry on outside it.
So the answer is it depends, if you want to miss out an item and carry on looping after the return statement then doing a return isn't what you want.
The return you put outside of the loop allows the loop to complete before returning the result.
Note a useful keyword you can use inside a loop if you want to finish the iteration rather than breaking the whole loop is continue.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue
I don't think one is wrong necessarily. I actually prefer a slightly different approach.
For clarity I generally will do something like this. So it is clearly one or the other.
With a return it is obvious that calculations within the function stop at that point. I just like it to look obvious.
if(charOne === charTwo && charOne === charThree) {
return false;
} {
return true;
}

Nested IF-FOR-IF loops

I'm stuck in nested loops.
this.isRyt is a variable where a retrived string from JSON is stored.
i is a user input variable of type string.
this.storeArray[] is an array where every input of i from user will be stored only if it matches the string stored in this.isRyt variable.So basically I want to compare the strings stored in this.storeArray[] by using index k to the string stored in this.isRryt(as multiple i inputs from user will stored at different index locations in this.storeArray[]),and if the string is not matched then there is variable counter which will get incremented.incCounter is nothing but a simple counter variable initialized with value 0.
My try: I tried using the below loop , but this.counter++ get incremented multiple times in a single time(multiple iterations of k) as it is inside the for loop. I want to make it increment only a single time but the for condition should not be omitted.
filterAnswer(i:any) //Comparing Answer submitted by user with JSON answer
{
this.isRyt = this.questArrayNew1[0].isRight;
if(this.isRyt == i )
{
for(let k = 0 ; k < this.questArray.length ; k++)
{
if(this.storeArray[k] == i)
{
console.log(k);
}
else
{
this.counter++; //WANT TO INCREMENT ONLY ONE TIME IF IT DOESNT SATISFY THE CONDITION FOR WHOLE K=0,1,2,3.. variable
}
}
this.storeArray[this.incCounter] = i ;
console.log(this.storeArray);
this.incCounter++;
}
else
{
return 0;
}
}
If I am understanding you correctly, this.counter only needs to be incremented once. You could try something like this:
filterAnswer(i:any) //Comparing Answer submitted by user with JSON answer
{
var notCounted = true; //condition for this.counter++ code block to be executed
this.isRyt = this.questArrayNew1[0].isRight;
if(this.isRyt == i )
{
for(let k = 0 ; k < this.questArray.length ; k++)
{
if(this.storeArray[k] == i)
{
console.log(k);
}
else
{
while(notCounted)
{ //executes while bool is true
this.counter++;
notCounted = false; //incremented so now no longer needed
}
}
}
this.storeArray[this.incCounter] = i ;
console.log(this.storeArray);
this.incCounter++;
}
else
{
return 0;
}
}

The following code only produces an output true. How to debug it?

I have the following code to generate prime numbers. However, instead of generating prime number, it generates the entire list on numbers from 2 to the number that is fed into the function. How to resolve this?
var i = 2;
var primeCheck = function(number){
while(i<number){
if(number%i===0)
{
break;
}
i++;
}
if (i===number)
{
return true;
}
};
var primeGen = function(limit){
for(k=2; k<=limit; k++)
{
if(primeCheck(k)){
console.log(k);
}
}
};
primeGen(10);
EDIT: I realized that I was quite unclear with my question. So I updated it. My guess is that the "return true" is causing this nuisance. Therefore I had asked my previous question based on that.
If you want to return something you have to return instead of alert; break. I would consider refactoring this though. First of all, you should never have a function that performs such a simple task rely on an outside variable. Keep it modular.
function isPrime(num) {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return num > 1
}
This will return true if the number is prime and false otherwise. This is useful because you now have the flexibility to do multiple things with it. If you want to return true or false, it does that. If you want to output something else like "prime" or "not prime" it's very easy to wrap further.
function isPrimeText(num) {
return isPrime(num) ? "Prime" : "Not Prime"
}
Your if condition that returns the alert runs with primecheck() without parameters. Correct it to:
if (primeCheck(11)) {
alert("prime");
}
Also, remove the last line with the call to primeCheck(11).
Just use primeCheck(11) in your condition where you want to put alert
There is some error in your logic, when I try with primeCheck(12) it does not gives intended result.
var i = 2;
var primeCheck = function(number){
while(i<Math.floor(Math.sqrt(number))){
if(number%i===0)
{
alert("Not a prime");
break;
}
i++;
}
if (i===Math.floor(Math.sqrt(number)))
{
return true;
}
};
//now check for prime or not prime
if(primeCheck(11))
{
alert("prime");
}
if(!primeCheck(12))
{
alert("not prime");
}

Counting unknown/dynamic array length of class element

I wrote a simple code/userscript to notify me about changes on a webiste:
function notifier(){
setTimeout(function () {
location.reload(true);
},60000)
}
function notiCounter() {
console.log("Counting notifications");
var noti = document.getElementsByClassName("notification");
for(var i = 0; i < 2; i++) {
if(noti[i].innerHTML != undefined) {
console.log(noti[i].innerHTML);
notifications++;
console.log("Notifications: " + notifications);
}
}
}
function notification(){
setTimeout(function () {
notiCounter();
if(notifications > 0){
document.title = "(" + notifications + ") new notifcations";
sound.play();
}
notifier();
},50)
}
notification();
The problem is, that the actual final number of noti[i] is unknown/dynamic and changes all the time, so if i < 2 is replaced with a higher number the for loop ends up in an infinite loop - and if I pick it too low (2 for example), data will gets lost if the actual number is above 2.
Any idea about that problem? Maybe it's really obvious and I can't see, as it is really late haha.
Rather than checking for i < 2, check for i < noti.length. Or you can iterate through using a for(var i in noti) type loop. Or better yet, if you just want the number of notifications directly, just use the value in noti.length

How to pass a integer into a javascript function?

I am getting a response from ajax request(done by jquery).
I have a method that displays errors to the users. Sometimes though I have some other information coming along with the json request.
So I don't want this info shown(where the rest of the errors are). So I figured since I always know the length of the json coming back I can just shorten the length since the error method just uses a while loop so if it is one less then it won't display that json part.
So I did this
var length = result.length -1;
ErrorsMethod(result, length); // call function.
function ErrorsMethod(result, length)
{
while( i < length)
{
// do stuff.
}
}
length is always undefined when it gets passed in though. I don't understand why.
I then tried
length.length
ParseInt(length);
None seems to work. I don't even know what I am working with. When I do an alert of "length" var before it goes into the function it spits out a number.
Were you correctly calling parseInt?
var length = parseInt(result.length) - 1;
ErrorsMethod(result, length);
ErrorsMethod(result, length); // call function.
function ErrorsMethod(result, length)
{
while( i < length)
{
// do stuff.
}
}
ErrorsMethod(result); // call function.
function ErrorsMethod(result)
{
if (result && result.length)
for ( var i = 0 ; i < result.length ; ++i )
{
// do stuff.
}
}
nor result or i are defined variables so thats probably why the script stops executing. try something like this:
<script type="text/javascript">
var result = [10, 2];
var length = result.length;
ErrorsMethod(result, length); // call function.
function ErrorsMethod(result, length)
{
var i=0;
while( i < length)
{
// do stuff.
alert(i);
i++;
}
}
</script>

Categories