使用 Plain Javascript 创建具有自定义格式的唯一标识符

Create unique identifier with custom format using Plain Javascript

我知道uuid的格式是XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX。 但我不想创建一个 uuid,我想创建一个具有不同格式的唯一标识符,例如 XXX-XXXX-XXX.

我如何使用纯 javascript 而不使用库来做到这一点。

有没有办法确保标识符是唯一的?

这是一个示例,说明如何创建一个独特的假 uuid 外观字符串。请注意,这不是真正的 uuid。

let uuids = [];

function getRandomUuidChar(count = 1) {
  // valid uuid chars: 0-9, a-f, A-F
  const chars = "1234567890abcdefABCDEF".split('');
  let retval = "";
  for (let i = 0; i < count; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    retval += chars[randomIndex];
  }
  return retval;
}

function generatePseudoUuid() {
  //  XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  const charCounts = [8, 4, 4, 4, 12];
  const uuid = charCounts
    .reduce((retval, count) => {
      retval.push(getRandomUuidChar(count));
      return retval;
    }, [])
    .join("-");
  if (!uuids.includes(uuid)) {
    uuids.push(uuid);
    return uuid;
  }
  generateUuid();
}
for(let i=0; i<10; i++){
  console.log("uuid", generateUuid());
}
console.log(uuids);

输出:

uuid 05D9F4C4-ddd8-9ff4-B5F3-c834E5da6F64
uuid 10dc0BCb-1DfD-8efB-EA7c-3f056930315C
uuid 8e5a21C0-EDD9-f3bc-bEBb-bbADe542342E
uuid b484Ca84-Ce89-eb91-94F4-8216b86A7245
uuid De70ABB8-D4E9-DBba-7783-b8109E1b5E27
uuid F1BF66b8-5458-B8d1-DA0c-6BceBea2ccc0
uuid aEffE093-faf8-FBA2-bb88-08865b446412
uuid a3AabDBC-2B4A-AcBc-8afF-8c0deCCeA92C
uuid C7b4DFaA-Da41-041a-FFfE-28064ABF5FB7
uuid E3F2F592-3AEc-aBdD-AC9c-304Dc93ceDa9
[
  '05D9F4C4-ddd8-9ff4-B5F3-c834E5da6F64',
  '10dc0BCb-1DfD-8efB-EA7c-3f056930315C',
  '8e5a21C0-EDD9-f3bc-bEBb-bbADe542342E',
  'b484Ca84-Ce89-eb91-94F4-8216b86A7245',
  'De70ABB8-D4E9-DBba-7783-b8109E1b5E27',
  'F1BF66b8-5458-B8d1-DA0c-6BceBea2ccc0',
  'aEffE093-faf8-FBA2-bb88-08865b446412',
  'a3AabDBC-2B4A-AcBc-8afF-8c0deCCeA92C',
  'C7b4DFaA-Da41-041a-FFfE-28064ABF5FB7',
  'E3F2F592-3AEc-aBdD-AC9c-304Dc93ceDa9'
]