Skip to content

Instantly share code, notes, and snippets.

@mildronize
Created November 8, 2020 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mildronize/b9ee884c1af6670298b97ddf737f70a9 to your computer and use it in GitHub Desktop.
Save mildronize/b9ee884c1af6670298b97ddf737f70a9 to your computer and use it in GitHub Desktop.
Global store
export type Dictionary<T> = {
[key: string]: T;
};
export class GlobalStore {
static get(key: string) {
if (getGlobalStore().data === undefined)
getGlobalStore().data = {};
if (getGlobalStore().data[key] === undefined)
return undefined;
return getGlobalStore().data[key].value;
}
static set(key: string, value: any) {
setGlobalStore(key, { value, editable: true });
return true;
}
static setConst(key: string, value: any) {
setGlobalStore(key, { value, editable: false });
return true;
}
}
function setGlobalStore(key: string, data: DataItem) {
if (getGlobalStore().data === undefined)
getGlobalStore().data = {};
if (isEditable(key)) {
getGlobalStore().data[key] = data;
} else {
throw new Error(`Can't modify value, because '${key}' is constant.`);
}
}
function isEditable(key: string) {
if (getGlobalStore().data === undefined)
return true;
if (getGlobalStore().data[key] === undefined)
return true;
const editable = getGlobalStore().data[key].editable;
return editable === undefined ? false : editable;
}
type DataItem = {
value: any,
editable: boolean
}
class Store {
data: Dictionary<DataItem>;
}
/**
* Gets global store.
*/
function getGlobalStore(): Store {
if (!(global as any).mildjsDiGlobalStore)
(global as any).mildjsDiGlobalStore = new Store();
return (global as any).mildjsDiGlobalStore;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment