Not yet rated

Problem

How to generate a valid UUID from a string, such as a combination of two other UUIDs. This is useful for creating a single unique identifier from another set of unique identifiers.

Solution

The solution is actually rather simple, simply create a HASH() of the input string and then format it so that it is a valid CF UUID.

Detailed explanation

Creating a hash of the incoming string will return a 32-character string that contains valid UUID characters, but is not in a UUID format.  After we have hash()'d the incoming string, we do a simple formatting of the hash value.

Proper UUIDs use the first character of the third character block to identify what type of UUID has been generated. Because this is a UUID generated from a hash, this value is set to a "3".

<cffunction name="createUUIDFromString" access="public" output="false" returntype="string">
    <cfargument name="value" type="string" required="true" />
    
    <cfset var hashString    = hash( arguments.value ) />
    <cfset var newUUID       = left(hashString,8) & "-" & mid(hashString,9,4) & "-" & "3" & mid(hashString,13,3) & "-" & right(hashString,16) />

    <cfreturn newUUID />
</cffunction>

This is very useful for uniting two unique identifiers into a new one.  For instance, if you had product code X and shopping cart Y, you could combine ID's X + Y = unique id.  The hash value of a specific string of characters will always be the same, so this string will always return the same UUID. The caveat is that you can't reverse engineer the new UUID; in other words, you can't get ID X or Y back out of the new UUID. 

Note that the incoming string can be anything from "Please make this a UUID" to existing UUIDs to integers to ... well, you get the idea.


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes