Skip to content

Instantly share code, notes, and snippets.

@dandean
Created August 5, 2009 19:11
Show Gist options
  • Save dandean/162884 to your computer and use it in GitHub Desktop.
Save dandean/162884 to your computer and use it in GitHub Desktop.
Guid class for generating and working with Guid-formatted strings...
/**
* class Guid
**/
var Guid = Class.create((function() {
var _value;
return {
/**
* new Guid(value);
*
* - value ([[String]]): Valid guid-formatted string.
**/
initialize: function(value) {
if (Guid.isGuid(value)) {
_value = value.toString(); return;
}
throw "Invalid GUID value: \"#{value}\"".interpolate({value: value});
},
/**
* Guid#isEmpty() -> Boolean
*
* Checks if the instance is empty.
**/
isEmpty: function() {
return _value == Guid.Empty;
},
/**
* Guid#equals(guid) -> Boolean
* - guid (Object): Value to compare against.
*
* Checks if the provided guid is the "same" as this instance. Comparison
* will return true if specified object's toString method returns the same
* value as this instance's value.
**/
equals: function(guid) {
return Guid.isGuid(guid) && this == guid;
},
/**
* Guid#toString() -> String
*
* Returns the Guid is [[String]] format.
**/
toString: function() { return _value; }
};
})());
Object.extend(Guid, (function() {
function _gen(count) {
// Private function for creating guid parts.
var out = "";
for (var i=0; i<count; i++) {
out += (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
return out;
}
return {
Empty: "00000000-0000-0000-0000-000000000000",
Validator: new RegExp("[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}", "i"),
/**
* Guid.isGuid(value) -> Boolean
* - value (Object): The value to check.
*
* Checks if the value represents a valid Guid. Value can be any object
* that returns a valid Guid-formatted string with its toString method.
**/
isGuid: function(value) {
return value && Guid.Validator.test(value.toString());
},
/**
* Guid.create() -> Guid
*
* Creates a new Guid object with a pseudo-unique value.
**/
create: function() {
return new Guid([_gen(2), _gen(1), _gen(1), _gen(1), _gen(3)].join("-"));
}
};
})());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment