Languages
[Edit]
EN

JavaScript - UUID function in Vanilla JS

6 points
Created by:
Creg
9150

In this article, we are going to show how in pure JavaScript write a custom UUID v4 generator (RFC4122).

The article contains different ways that show how to implement UUID v4 generator.

From Wikipedia:

A universally unique identifier (UUID) is a 128-bit number used to identify information in computer systems. The term globally unique identifier (GUID) is also used, typically in software created by Microsoft.

Hint: at the end of the article you will find a performance comparison.

 

Most popular version example

This is the common version that can be found on the internet.

Important note: main disadvantage of this solution is weak performance.

// ONLINE-RUNNER:browser;

function uuidv4() {
    return '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);
    });
}


// Usage example:

console.log(uuidv4());
console.log(uuidv4());
console.log(uuidv4());
console.log(uuidv4());

 

Custom implementation example

This implementation is more than 2 times faster than the first one because do not use replace() method.

// ONLINE-RUNNER:browser;

var UUIDv4 = new function() {
	function generateNumber(limit) {
	   var value = limit * Math.random();
	   return value | 0;
	}
	function generateX() {
		var value = generateNumber(16);
		return value.toString(16);
	}
	function generateXes(count) {
		var result = '';
		for(var i = 0; i < count; ++i) {
			result += generateX();
		}
		return result;
	}
	function generateVariant() {
		var value = generateNumber(16);
		var variant =  (value & 0x3) | 0x8;
		return variant.toString(16);
	}
    // UUID v4
    //
    //   varsion: M=4 
    //   variant: N
    //   pattern: xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
    //
	this.generate = function() {
  	    var result = generateXes(8)
  	         + '-' + generateXes(4)
  	         + '-' + '4' + generateXes(3)
  	         + '-' + generateVariant() + generateXes(3)
  	         + '-' + generateXes(12)
  	    return result;
	};
};


// Usage example:

console.log(UUIDv4.generate());
console.log(UUIDv4.generate());
console.log(UUIDv4.generate());
console.log(UUIDv4.generate());

 

Methods performance comparison example

A simple performance comparison for the above methods is presented in this section.

Performance test result made on Ryzen 9:

uuidv4()         : totoal time is 178 ms
UUIDv4.generate(): totoal time is 70 ms

Used code:

// ONLINE-RUNNER:browser;

// test logic

// Source: https://dirask.com/posts/JavaScript-test-algorithm-performance-D6nXnD
//
const test = (repeats, description, func) => {
	const t1 = Date.now();
  	for (let i = 0; i < repeats; ++i) {
  		func();
    }
  	const t2 = Date.now();
  	const dt = t2 - t1;
  	console.log(`${description}: totoal time is ${dt} ms`);
};


// method 1 logic

// copied from the above example
//
const uuidv4 = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
};


// method 2 logic

// copied from the above example
//
const UUIDv4 = new function() {
	const generateNumber = (limit) => {
	   const value = limit * Math.random();
	   return value | 0;
	};
	const generateX = () => {
		const value = generateNumber(16);
		return value.toString(16);
	};
	const generateXes = (count) => {
		let result = '';
		for(let i = 0; i < count; ++i) {
			result += generateX();
		}
		return result;
	};
	const generateVariant = () => {
		const value = generateNumber(16);
		const variant = (value & 0x3) | 0x8;
		return variant.toString(16);
	};
    // UUID v4
    //
    //   varsion: M=4 
    //   variant: N
    //   pattern: xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
    //
	this.generate = function() {
  	    const result = generateXes(8)
  	           + '-' + generateXes(4)
  	           + '-' + '4' + generateXes(3)
  	           + '-' + generateVariant() + generateXes(3)
  	           + '-' + generateXes(12)
  	    return result;
	};
};


// Methods comparison:

const repeats = 100000; // number of repeats depending

test(repeats, 'uuidv4()         ', () => uuidv4());
test(repeats, 'UUIDv4.generate()', () => UUIDv4.generate());

 

See also

  1. JavaScript - generate unique id (useful in web browser)

  2. JavaScript - test algorithm performance

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join