Monday, November 10, 2014

A Trio of Helpful Functions

Today I'd like to share three very small but useful JavaScript functions I found while building 2-Player Solitaire.

First, you can't have a card game without shuffling the deck. I found this shuffle function on http://jsfromhell.com/array/shuffle. In just a few lines, it randomizes the order of elements in a given array. Every day I'm shufflin'...

function shuffle(v) {
    for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
    return v;
}

The second one is the function I use to create game ids. The games are identified by 5-character case-sensitive alphanumeric strings. It's easy to get ids of a different length, just change the number of iterations through the loop.

function makeGameId() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for( var i=0; i < 5; i++ ) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
}

Finally, there is this beautiful function for creating random GUIDs. This one is from http://byronsalau.com/blog/how-to-create-a-guid-uuid-in-javascript/. I use this to generate the unique identifiers for the cards in the game.

function createGuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
    });
}

I hope these can be as helpful to you as they have been to me.

Amphibian.com comic for 10 November 2014