Различные методы генерации случайных идентификаторов в JavaScript

Вот несколько способов создания случайного идентификатора в JavaScript:

Метод 1: использование Math.random() и Math.floor():

const randomId = () => {
  const length = 10; // Adjust the length of the ID as needed
  let id = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;

  for (let i = 0; i < length; i++) {
    id += characters.charAt(Math.floor(Math.random() * charactersLength));
  }

  return id;
};
const id = randomId();
console.log(id);

Метод 2. Использование объекта Date:

const randomId = () => {
  const timestamp = new Date().getTime().toString();
  const random = Math.random().toString().substring(2);
  const id = timestamp + random;
  return id;
};
const id = randomId();
console.log(id);

Метод 3: использование UUID (универсального уникального идентификатора):

const randomId = () => {
  const id = '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);
  });

  return id;
};
const id = randomId();
console.log(id);

Метод 4. Использование crypto.getRandomValues() (требуется поддержка браузера):

const randomId = () => {
  const array = new Uint32Array(1);
  window.crypto.getRandomValues(array);
  const id = array[0].toString();
  return id;
};
const id = randomId();
console.log(id);

Метод 5. Использование библиотеки nanoid (требуется установка):

const { nanoid } = require('nanoid');
const randomId = () => {
  const id = nanoid();
  return id;
};
const id = randomId();
console.log(id);