w3resource

JavaScript: Function to create a UUID identifier

JavaScript Math: Exercise-23 with Solution

Write a JavaScript function to create a UUID identifier.

Note :
According to Wikipedia - A universally unique identifier (UUID) is an identifier standard used in software construction. A UUID is simply a 128-bit value. The meaning of each bit is defined by any of several variants. For human-readable display, many systems use a canonical format using hexadecimal text with inserted hyphen characters. For example : de305d54-75b4-431b-adb2-eb6b9e546014

Sample Solution:-

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Write a JavaScript function to create a UUID</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function create_UUID(){
    var dt = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (dt + Math.random()*16)%16 | 0;
        dt = Math.floor(dt/16);
        return (c=='x' ? r :(r&0x3|0x8)).toString(16);
    });
    return uuid;
}

console.log(create_UUID());

Sample Output:

1fe35579-5ce7-46ec-89e0-7e7236700297

Flowchart:

Flowchart: JavaScript Math- Function to create a UUID identifier

Live Demo:

See the Pen javascript-math-exercise-23 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function that Convert Roman Numeral to Integer.
Next: Write a JavaScript function to round a number to a specified number of digits and strip extra zeros (if any).

What is the difficulty level of this exercise?



JavaScript: Tips of the Day

Removes elements in an array until the passed function returns true. Returns the removed elements.

Example:

const tips_remove = (arr, func) => {
  for (const [i, val] of arr.entries()) if (func(val)) return arr.slice(0, i);
  return arr;
};

console.log(tips_remove([1, 2, 3, 4, 5, 6], n => n >= 5));

Output:

[1, 2, 3, 4]