A
A
Alexander2020-05-04 17:55:18
JavaScript
Alexander, 2020-05-04 17:55:18

Why is there a shift in this function?

I found a UUID generation function on the Internet:

const uuid =()=>([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,c=>(c^crypto.getRandomValues(new Uint8Array(1))[0]&15 >> c/4).toString(16));

Explain the work. In particular, why shift? Well, everything else.

To make it clear - if I wrote such a function, with the same approach, then it would look something like this:
const uuid =()=>([1e7]+-1e3+-1e3+-1e3+-1e11).replace(/[01]/g,()=>(crypto.getRandomValues(new Uint8Array(1))[0]&15).toString(16));

Although most likely instead of & in general there would be a module or XOR.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Grigory Boev, 2020-05-04
Madzhugin @Suntechnic

1) ([1e7]+-1e3+-4e3+-8e3+-1e11) - the string "10000000-1000-4000-8000-100000000000" is formed
2) .replace(/[018]/g,c= - run through the characters, and do something with every 0, 1 and 8
3) 15 >> c/4 - 0,1,8 => 15,15,3
4) crypto.getRandomValues(new Uint8Array(1))[0] - random number 0..255
5) crypto.getRandomValues(new Uint8Array(1))[0]&15 >> c/4 - bitwise AND narrows 0..255 to 0..15 or 0..3 (if c=8)
6 ) c^crypto.getRandomValues(new Uint8Array(1))[0]&15 >> c/4 - 0 or 1 or 8 XOR with 5)
7) What happened - translated into HEX and returned instead of character
Shift and XOR (3) and 6) ) are probably needed for higher entropy, although it works without it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question