function getRandumNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
Random number with fixed length
Generate a random number with fixed length.
Example:
function getRandumNumber(length) {
const min = Math.pow(10, (length-1));
const max = Math.pow(10, (length));
return Math.floor(Math.random() * (max - min) + min);
}
Random string
Example:
function getRandomString(length) {
const allowedCharacters = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const allowedCharacterLength = allowedCharacters.length;
let result = '';
for ( let i = 0; i < length; i++ ) {
result += allowedCharacters.charAt(Math.floor(Math.random() * allowedCharacterLength));
}
return result;
}
Random UUID
Example:
function getUUID() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
Random color
Example:
function getRandomColor() {
const availableCharacters = '0123456789ABCDEF';
const availableCharacterLength = availableCharacters.length;
let color = '#';
for (let i = 0; i < 6; i++) {
color += availableCharacters[Math.floor(Math.random() * availableCharacterLength)];
}
return color;
}
Random date
Example:
function getRandomDate() {
const maxDate = Date.now();
const timestamp = Math.floor(Math.random() * maxDate);
return new Date(timestamp);
}