somejonus somejonus - 5 months ago 10
Node.js Question

Looping the inside of a function until goal is met

I have an array of users called

randomUserArray
. From there I want to retrieve a random user and pass it on. If the chosen user is the same as
clientNickname
I need the function to start over so it wont return a
randomRecipient
that is also the
clientNickname
. Right now my function will return them anyway.

function randomRecipientCalc (clientNickname){

var randomRecipient = randomUserArray[Math.floor((Math.random() * randomUserArray.length) + 0)];

while (randomRecipient == clientNickname) {

randomRecipient = randomUserArray[Math.floor((Math.random() * randomUserArray.length) + 0)];

}

return randomRecipient;

}


Let's say I have two users in my array (wich would be the minimum at any given time)

`var randomUserArray = ["user1","user2"]`


and "user1" also being the client

var clientNickname = "user1"


then I use

var Recipient = randomRecipientCalc();


to get the user the function chose. Is this case it needs to be "user2".
If it ins't, meaning

randomRecipient == clientNickname


I have console print an error. Wich it does right now.

Answer

You can simplify the problem by removing the duplicate element. Example:

var temporaryRandomUserArray = randomUserArray.filter(function(ele) {
    return !(ele === clientNickname); // keep if ele not equal to clientNickname
});
temporaryRandomUserArray[Math.floor((Math.random() * randomUserArray.length) + 0)];
...
..

Something like this is neat and clear. No need of a recursive function call.