Generating GUIDs in JavaScript

My last few projects required the use of GUIDs in a variety of ways.  While searching for an all JavaScript approach, I stumbled across a great stackoverflow question “How to create a GUID / UUID in Javascript?”Broofa provided an elegant solution to this problem which I’ve placed into a CommonJS module to make it easy to use in Titanium.

CommonJS Module:

exports.generate = function(){
	var guid = '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);
	});		
	return guid;
};

View as gist

Generating a GUID in Titanium:

Ti.API.info("Require the CommonJS module");
var guid = require("guidtools");

Ti.API.info("Requesting a new guid");
Ti.API.info("GUID value = " + guid.generate());

View as gist

The above generates the below in your console window.

GUIDOutput

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s