Created
November 8, 2020 17:33
-
-
Save mildronize/b9ee884c1af6670298b97ddf737f70a9 to your computer and use it in GitHub Desktop.
Global store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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