global-const
Version:
A lightweight utility to create global singletons (on browser and node)
61 lines • 2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.clearGlobalNamespace = exports.getGlobalisedValue = void 0;
const GLOBALISE_KEY_PREFIX = "globalise__singleton__";
const fallbackGlobal = {};
const getGlobalObject = () => {
if (typeof window !== "undefined") {
return window;
}
if (typeof globalThis !== "undefined") {
return globalThis;
}
return fallbackGlobal;
};
const validateInputs = (namespace, key) => {
if (typeof namespace !== "string") {
throw "Invalid namespace key";
}
if (typeof key !== "string") {
throw "Invalid item key";
}
};
const createGlobalisedKey = (namespace) => {
return `${GLOBALISE_KEY_PREFIX}${namespace}`;
};
const getGlobalScopedObject = (namespace) => {
const globalObject = getGlobalObject();
const GLOBALISE_KEY = createGlobalisedKey(namespace);
// Initialise global object
if (!globalObject[GLOBALISE_KEY]) {
globalObject[GLOBALISE_KEY] = {};
}
return globalObject[GLOBALISE_KEY];
};
const getSingleton = (namespace, key) => {
const scopedObject = getGlobalScopedObject(namespace);
return scopedObject[key] || undefined;
};
const setSingleton = (namespace, key, value) => {
const scopedObject = getGlobalScopedObject(namespace);
scopedObject[key] = value;
};
const getGlobalisedValue = (namespace, key, value) => {
validateInputs(namespace, key);
const existing = getSingleton(namespace, key);
if (existing !== undefined) {
return existing;
}
setSingleton(namespace, key, value);
return value;
};
exports.getGlobalisedValue = getGlobalisedValue;
const clearGlobalNamespace = (namespace) => {
const globalObject = getGlobalObject();
const globalisedKey = createGlobalisedKey(namespace);
if (globalObject[globalisedKey] !== undefined) {
delete globalObject[globalisedKey];
}
};
exports.clearGlobalNamespace = clearGlobalNamespace;
//# sourceMappingURL=lib.js.map