Created
November 29, 2013 09:38
-
-
Save roobie/7703493 to your computer and use it in GitHub Desktop.
UUID impl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Guid = (function() { | |
/// Constructor: | |
function Guid() { | |
this.bytes = (function rec(acc, i) { | |
return (0 > i || i > 31) ? | |
acc : | |
rec(acc.concat((Math.random() * 16 | 0).toString(16)), i + 1); | |
})([], 0); | |
} | |
/// `Static` formats: | |
Guid.formats = [ | |
"NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN", | |
"NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN", | |
"{NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN}", | |
"(NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN)", | |
"{0xNNNNNNNN,0xNNNN,0xNNNN,{0xNN,0xNN,0xNN,0xNN,0xNN,0xNN,0xNN,0xNN}}", | |
]; | |
Guid.empty = (function(){ | |
var g = new Guid(); | |
g.bytes = Guid.formats[0].replace(/N/g, "0").split(""); | |
return g; | |
})(); | |
/// `Static` default format: | |
Guid.defaultFormat = Guid.formats[1]; | |
Guid.prototype.toString = function Guid_toString(format) { | |
var self = this; | |
if (format === void 0 || format === null) { | |
format = Guid.defaultFormat; | |
} else { | |
format = Guid.formats[format] || Guid.defaultFormat; | |
} | |
return (function() { | |
var bs = self.bytes.slice(), | |
maxi = format.length, | |
result = [], i; | |
if (format.split("N").length !== 33) { | |
throw new Error("There has to be exactly 32 `N` in the format string."); | |
} | |
for (i = 0; i < maxi; i++) { | |
if (format[i] === "N") { | |
result.push(bs.shift()); | |
} else { | |
result.push(format[i]); | |
} | |
} | |
return result.join(""); | |
})(); | |
}; | |
Guid.prototype.valueOf = function Guid_valueOf() { | |
return this.toString(0); | |
}; | |
Guid.prototype.equals = function Guid_equals(other) { | |
return this.valueOf() === other.valueOf(); | |
}; | |
return Guid; | |
})(); | |
//var g = new Guid; | |
//console.log(g.toString(), g.toString(0), g.toString(1), g.toString(2), g.toString(3), g.toString(4)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment