All files / src/apis/shared uuid.ts

100% Statements 15/15
100% Branches 1/1
100% Functions 3/3
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 516x               6x 6x   6x 6x   6x 96x     6x                         6x                       96x 96x   80x 80x 80x    
import { randomBytes } from "./platform/crypto";
 
/**
 * Генерирует UUID
 *
 * @export
 * @return {string}
 */
export function generateUUID(): string {
  const bytes = randomBytes(16);
 
  bytes[6] = (bytes[6] & 0x0f) | 0x40;
  bytes[8] = (bytes[8] & 0x3f) | 0x80;
 
  const plain = Array.from(bytes)
    .map((byte) => byteToString(byte))
    .join("");
 
  return (
    plain.slice(0, 8) +
    "-" +
    plain.slice(8, 12) +
    "-" +
    plain.slice(12, 16) +
    "-" +
    plain.slice(16, 20) +
    "-" +
    plain.slice(20, 32)
  );
}
 
const cache = new Map<number, string>();
 
/**
 *
 *
 * @param {number} byte
 * @return {string} string
 *
 * @example
 * byteToString(255) // -> "ff"
 */
function byteToString(byte: number): string {
  const cached = cache.get(byte);
  if (typeof cached === "string") return cached;
 
  const value = byte.toString(16).padStart(2, "0");
  cache.set(byte, value);
  return value;
}