Typescript: LocalStorage helper functions

Date: 2021-09-22
const getCircularReplacer = () => {
    const seen = new WeakSet();
    return (key: any, value: any) => {
        if (typeof value === "object" && value !== null) {
            if (seen.has(value)) {
                return;
            }
            seen.add(value);
        }
        return value;
    };
};

const toJson = (x: any) => JSON.stringify(x, getCircularReplacer());

const parseJson = (x: any) => {
    if (typeof x !== "string") return undefined;
    try {
        return JSON.parse(x);
    } catch {
        return undefined;
    }
};

const getLocalStorage = <T>(key: string): T => parseJson(localStorage.getItem(key)) as T;
const setLocalStorage = (key: string, state: any): any => localStorage.setItem(key, toJson(state));

const createGuid = (): string => {
    let d = new Date().getTime();
    const uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
        const r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        // eslint-disable-next-line no-mixed-operators
        return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
};
53700cookie-checkTypescript: LocalStorage helper functions