Search code examples
javascriptuuidguidwebcrypto-api

JavaScript constructing UUID from two long numbers


I have two long number that i represent those in JavaScript using BigInt ( because of the 53 bit integer length in JavaScipt instead of 64 bit). I found myself in the need to create out of those two long number an UUID / GUID in JavaScript.

In SO i was able to find the same question multiple times but always for different programming languages but not for JavaScript, example here:

Basically i am looking for something like the one in Java i.e. example here:

public UUID(long mostSigBits, long leastSigBits) {
    this.mostSigBits = mostSigBits;
    this.leastSigBits = leastSigBits;
}

and we can use it like:

UUID  tempUUID1 = new UUID(55, 100);

results in :

00000000-0000-0037-0000-000000000064

The approach that i am thinking to take so far is convert the decimal to hex like that

 BigInt("55").toString('16')     // results to 37
 BigInt("100").toString('16')    // results to 64

and then pad the missing zeros. How such function can be implemented, I am looking for an example.

Preferably using the WebCryptoAPI (unfortunately node.js is not what i am looking for here), that can create and read/split such UUID / GUID to 2 separate BigInt's i.e. the "mostSigBits" and the "leastSigBits" values.

I would really appreciate if someone provides an example of such function / method . Thank you in advanced.


Solution

  • There's no need for a library, formatting these numbers is fairly straightforward substring'ing:

    function formatAsUUID(mostSigBits, leastSigBits) {
        let most = mostSigBits.toString("16").padStart(16, "0");
        let least = leastSigBits.toString("16").padStart(16, "0");
        return `${most.substring(0, 8)}-${most.substring(8, 12)}-${most.substring(12)}-${least.substring(0, 4)}-${least.substring(4)}`;
    }
    

    function formatAsUUID(mostSigBits, leastSigBits) {
        let most = mostSigBits.toString("16").padStart(16, "0");
        let least = leastSigBits.toString("16").padStart(16, "0");
        return `${most.substring(0, 8)}-${most.substring(8, 12)}-${most.substring(12)}-${least.substring(0, 4)}-${least.substring(4)}`;
    }
    
    
    const expect = "00000000-0000-0037-0000-000000000064";
    const result = formatAsUUID(BigInt("55"), BigInt("100"));
    console.log(result, expect === result ? "OK" : "<== Error");