54 lines
1.4 KiB
TypeScript
54 lines
1.4 KiB
TypeScript
|
/**
|
||
|
* @author Martin Karkowski
|
||
|
* @email m.karkowski@zema.de
|
||
|
* @create date 2020-08-25 23:01:24
|
||
|
* @modify date 2020-08-25 23:08:42
|
||
|
* @desc [description]
|
||
|
*/
|
||
|
|
||
|
/**
|
||
|
* Function to get a singleton
|
||
|
* @param identifier
|
||
|
* @param create
|
||
|
*/
|
||
|
export function getSingleton<T>(identifier: string, create: () => T) {
|
||
|
// Extract all
|
||
|
const globalSymbols = Object.getOwnPropertySymbols(global);
|
||
|
|
||
|
// create a unique, global symbol name
|
||
|
// -----------------------------------
|
||
|
const IDENTIFIER_DISPATCHER_CONTAINER = Symbol.for(identifier);
|
||
|
|
||
|
// check if the global object has this symbol
|
||
|
// add it if it does not have the symbol, yet
|
||
|
// ------------------------------------------
|
||
|
const hasContainer = (globalSymbols.indexOf(IDENTIFIER_DISPATCHER_CONTAINER) > -1);
|
||
|
|
||
|
if (!hasContainer) {
|
||
|
global[IDENTIFIER_DISPATCHER_CONTAINER] = create();
|
||
|
}
|
||
|
|
||
|
const ret: {
|
||
|
instance: T,
|
||
|
setInstance: (value: T) => void
|
||
|
} = {
|
||
|
instance: global[IDENTIFIER_DISPATCHER_CONTAINER],
|
||
|
setInstance: (value: T) => {
|
||
|
global[IDENTIFIER_DISPATCHER_CONTAINER] = value;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// define the singleton API
|
||
|
// ------------------------
|
||
|
Object.defineProperty(ret, 'instance', {
|
||
|
get: function () {
|
||
|
return global[IDENTIFIER_DISPATCHER_CONTAINER];
|
||
|
}
|
||
|
});
|
||
|
|
||
|
// ensure the API is never changed
|
||
|
// -------------------------------
|
||
|
Object.freeze(ret);
|
||
|
|
||
|
return ret;
|
||
|
}
|