Gitsunmin

TIL

TIL
(=Today I Learned)

The easiest way to create UUID in JS

보통 UUID를 생성할 때는 uuid 라이브러리를 사용합니다. 하지만, 라이브러리를 사용하지 않고도 간단하게 UUID를 생성할 수 있습니다.

const uuid = () => {
  const s4 = () =>
    Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;
};

하지만 위에 방법은 가정 쉬운 방법은 아닙니다.

let uuid = self.crypto.randomUUID();
console.log(uuid); // uuid 값이 나옵니다.

crypto.randomUUID() 를 사용하면 간단하게 UUID를 생성할 수 있습니다.