Create a unique string (UUID) using JavaScript.

この記事は約3分で読めます。
スポンサーリンク

Things I want to do

This code creates a unique string (UUID) using JavaScript.

Specific example

We assign a unique string to each class and use it to verify instances instead of using pointers.

スポンサーリンク

implementation

A unique string (UUID) can be created in the following single line. (It will return a different string each time it is called.)

const uuid = self.crypto.randomUUID();

The return value is in the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx . (Example: d6436922-c138-4ef3-bab6-5de2546f847e )

I read the materials, but I couldn’t understand how they maintain their uniqueness.

The probability is low, but it doesn’t mean that the same value won’t be generated.

If necessary, perform a check to ensure that the issued UUID does not overlap with an already issued one.

Implementation of a concrete example

For the example ‘We’ll give the Class a unique string to use instead of a pointer to check the instance,’ the following implementation should work.

class tool {
    #uid;
    constructor(){
        this.#uid = self.crypto.randomUUID();
    }
    get uid(){return this.#uid}
}
スポンサーリンク

Websites I used as references

Crypto: randomUUID() メソッド - Web API | MDN
randomUUID() は Crypto インターフェイスのメソッドで、暗号強度の強い乱数生成器を用いて v4 UUID を生成するのに用いられます。

コメント

タイトルとURLをコピーしました