samedi 23 mai 2015

JS: Random String without Repeating Same String Twice

I'm trying to figure out a way to pull a random string from an array with pure JS, without the same string appearing twice in succession.

I'm using a random number (random number) to pull a random string from randomMsg using the random number's index, I'm then storing it in currentMsg.

On click, I'm then redefining the currentMsg with a new random string. I'm then using an if/else statement to see if our prevMsg is equal to currentMsg, if it is (which it isn't on first click), I'm using another if/else statement to increment or decrement our index, so it returns a unique string (anotherMsg) to our HTML and sets prevMsg var to that string.

Else, it returns the currentMsg to our HTML, and sets prevMsg equal to currentMsg.

Fucntion below:

(function message() {
    var ranNumber = Math.floor((Math.random() * 5) + 0);
    var randomMsg = [
      "string one",
      "string two",
      "string three",
      "string four",
      "string five"
    ];

    var currentMsg = randomMsg[Math.floor((Math.random() * 5) + 0)];
    var prevMsg = "";

    document.getElementById("intro").innerHTML = currentMsg;

    document.getElementById("intro").onclick = function() {
        var ranNum = Math.floor((Math.random() * 5) + 0);
        currentMsg = randomMsg[ranNum];
        if(prevMsg == currentMsg) {
            var anotherMsg = "";
            if(ranNum >= 0 && ranNum < 4) {
                anotherMsg = randomMsg[ranNum + 1];
            }
            else {
                anotherMsg = randomMsg[ranNum - 1];
            }
            document.getElementById("intro").innerHTML = anotherMsg;
            prevMsg = anotherMsg; // set prevMsg to anotherMsg
        } else {
            document.getElementById("intro").innerHTML = currentMsg;
            prevMsg = currentMsg; // set prevMsg to currentMsg
        };
    };
})();

I've also setup a JSFiddle here.

While it works, I'm eager to now if there's a more elegant approach to write such a function. Also I'm replacing the entire string, is it better to replace just the word (one, two, three, etc.) or doesn't that matter one bit?

Any help is appreciated. Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire