MCPcopy Create free account
hub / github.com/freeCodeCamp/freeCodeCamp / getUUID

Function getUUID

client/src/utils/growthbook-cookie.ts:1–38  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

1export const getUUID = () => {
2 const COOKIE_NAME = 'gbuuid';
3 const COOKIE_DAYS = 400; // 400 days is the max cookie duration for chrome
4
5 // use the browsers crypto.randomUUID if set
6 const genUUID = () => {
7 if (window?.crypto?.randomUUID) return window.crypto.randomUUID();
8
9 // return a random UUID style string`
10 return ((1e7).toString() + -1e3 + -4e3 + -8e3 + -1e11).replace(
11 /[018]/g,
12 c =>
13 (
14 Number(c) ^
15 (crypto.getRandomValues(new Uint8Array(1))[0] &
16 (15 >> (Number(c) / 4)))
17 ).toString(16)
18 );
19 };
20
21 const getCookie = (name: string) => {
22 const value = `; ${document.cookie}`;
23 const parts = value.split(`; ${name}=`);
24 if (parts.length === 2) return parts.pop()?.split(';').shift();
25 };
26 const setCookie = (name: string, value: string) => {
27 const d = new Date();
28 d.setTime(d.getTime() + 24 * 60 * 60 * 1000 * COOKIE_DAYS);
29 document.cookie = name + '=' + value + ';path=/;expires=' + d.toUTCString();
30 };
31
32 // get the existing UUID from cookie if set, otherwise create one and store it in the cookie
33 if (getCookie(COOKIE_NAME)) return getCookie(COOKIE_NAME);
34
35 const uuid = genUUID();
36 setCookie(COOKIE_NAME, uuid);
37 return uuid;
38};

Callers 2

GrowthBookWrapperFunction · 0.90

Calls 3

getCookieFunction · 0.85
genUUIDFunction · 0.85
setCookieFunction · 0.85

Tested by

no test coverage detected