Skip to content

Instantly share code, notes, and snippets.

@servercharlie
Created March 30, 2017 17:44
Show Gist options
  • Save servercharlie/70638dd74bec7b52223ef9794b47f83c to your computer and use it in GitHub Desktop.
Save servercharlie/70638dd74bec7b52223ef9794b47f83c to your computer and use it in GitHub Desktop.
SimpleUUID JS
// https://gist.github.com/jed/982883
// https://github.com/chriso/validator.js/blob/master/validator.js#L774-L787
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy
var uuidv4 = new Proxy(function(_removeDash){
function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)}
return _removeDash ? b().replace(/-/g, '') : b();
}, {
get(target, name) {
return {
validate: function(_uuid){
var uuid = {
3: /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,
4: /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,
5: /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,
all: /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i
};
if (typeof _uuid !== 'string') {
throw new TypeError('This library (validator.js) validates strings only');
}
var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'all';
var pattern = uuid[version];
return pattern.test(_uuid);
}
}[name];
}
});
// usage
console.log(uuidv4());
// uuidv4, without dash
console.log(uuidv4(true));
// uuidv4, without dash
console.log(uuidv4.validate(uuidv4()));
// tests across v3, v4 & v5
// true, since it matches v4
//
console.log(uuidv4.validate(uuidv4(true)));
// false, since dashes are expected.
console.log(uuidv4.validate(uuidv4(), '4'));
// specifically tests against v4
// true, checks for v4.
// you can also use 3 or 5. valid values are 3, 4 & 5
console.log(uuidv4.validate(uuidv4(), '3'));
// false of course.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment