[JavaScript]生成唯一id的一种方法

 

export const replaceCallback = (character: string) => {
  // Generate a random number between 0 and 15
  const randomNumber = (Math.random() * 16) | 0;

  // If the character in the UUID template is 'x', use the random number.
  // Otherwise, use the random number ANDed with 0x3 (which gives a number between 0 and 3) ORed with 0x8
  // (which sets the high bit, ensuring a number between 8 and 11).
  const uuidCharacter =
    character === "x" ? randomNumber : (randomNumber & 0x3) | 0x8;

  // Convert the number to a hexadecimal string and return it
  return uuidCharacter.toString(16);
};

export const generateUUID = () => {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
    /[xy]/g,
    replaceCallback
  );
};

来自:openmetadata

posted @ 2025-04-02 18:34  ximu19  阅读(50)  评论(0)    收藏  举报