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; };
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());
The above generates the below in your console window.