Elvis Ramirez
Elvis Ramirez

Reputation: 23

If and return in Nodejs or Java

I have this example code

var randFriend = friendList[Math.floor(Math.random() * friendList.length)];
if (randFriend == admin) {
    //Here
}
else if (randFriend != admin) {
    client.removeFriend(randFriend);
}

How can I do if if randfriend == admin to do again var randFriend = friendList[Math.floor(Math.random() * friendList.length)]; and check if(randFriend == admin) again. In other words, to restart that again.

I think that it's done with return, but I don't know. Thanks

Upvotes: 0

Views: 63

Answers (3)

t.niese
t.niese

Reputation: 40842

I wouldn't use recursion or loops with random conditions, because you will have problems to estimate the runtime, and if the use case changes and you would have more elements you want to ignore, then the probability to find the correct element will decrease.

A better idea would be to filter the array to remove the elements you want to ignore and then pick a random element from that list.

var nonAdminList = friendList.filter(person => person != admin);

if( nonAdminList.length === 0 ) {
  throw new Error('no non admin persons available');
}

client.removeFriend(nonAdminList[Math.floor(Math.random() * nonAdminList.length)]);

Upvotes: 1

littlespice3
littlespice3

Reputation: 141

If I'm understanding the question correctly, you could use a while loop to keep randomizing until an admin isn't selected

var friendAdmin = true;
var randFriend;
while(friendAdmin){
   randFriend = friendList[Math.floor(Math.random() * friendList.length)];
   if(randFriend != admin) friendAdmin = false;
}
client.removeFriend(randFriend);

Upvotes: 0

Ryan
Ryan

Reputation: 69

I would put your code into a function so that you can invoke the function again if you want to repeat it. For example:

function choose(){
        var randFriend = friendList[Math.floor(Math.random() * friendList.length)];
        if(randFriend == admin){
            choose(); //this repeats the choose function, which will run the random friend code again
        }
        else if(randFriend != admin){
            client.removeFriend(randFriend);
            return; //this exits the function
        }
    }

Upvotes: 0

Related Questions