JS generate UUID

Time:2022-5-23

UUID refers to universal unique identifier, which is translated into ChineseUniversal unique identification code

Coding rules

UUID (universal unique identifier) is a globally unique identifier. It is defined as a string primary key, which is composed of 32-bit digits and encoded in hexadecimal. It defines the system information that is completely unique in time and space.

Coding rules of UUID:

1) 1 ~ 8 bits adopt system time, which is accurate to milliseconds to ensure the uniqueness of time;
2) 9 ~ 16 bits adopt the underlying IP address, which is unique in the server cluster;
3) 17 ~ 24 bits adopt the hashcode value of the current object, which is unique on an internal object;
4) 25 ~ 32 bits adopt a random number of calling method, which is unique in milliseconds within an object.
Uniqueness can be guaranteed through the above four strategies. UUID algorithm can be considered where random numbers need to be used in the system.

Upper code

 const hexList = [];
      for (let i = 0; i <= 15; i++) {
        hexList[i] = i.toString(16);
      }

      function buildUUID() {
        let uuid = "";
        for (let i = 1; i <= 36; i++) {
          if (i === 9 || i === 14 || i === 19 || i === 24) {
            uuid += "-";
          } else if (i === 15) {
            uuid += 4;
          } else if (i === 20) {
            uuid += hexList[(Math.random() * 4) | 8];
          } else {
            uuid += hexList[(Math.random() * 16) | 0];
          }
        }
        return uuid.replace(/-/g, "");
      }

      let unique = 0;
      function buildShortUUID(prefix = "") {
        const time = Date.now();
        const random = Math.floor(Math.random() * 1000000000);
        unique++;
        return prefix + "_" + random + unique + String(time);
      }
      console.log(buildUUID());                  // 1a8ba5edde0542a18b06304b1bed5d7c
      console.log(buildShortUUID("test"));      // test_43581603011638886158139