nope/lib/helpers/singletonMethod.ts

56 lines
1.4 KiB
TypeScript
Raw Normal View History

2020-08-25 22:11:26 +00:00
/**
* @author Martin Karkowski
* @email m.karkowski@zema.de
* @create date 2020-08-25 23:01:24
2020-11-07 00:45:20 +00:00
* @modify date 2020-11-07 00:35:49
2020-08-25 22:11:26 +00:00
* @desc [description]
*/
/**
* Function to get a singleton
2021-12-04 07:25:26 +00:00
* @param identifier
* @param create
2020-08-25 22:11:26 +00:00
*/
export function getSingleton<T>(identifier: string, create: () => T) {
2021-12-04 07:25:26 +00:00
// Extract all
2020-08-25 22:11:26 +00:00
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
// ------------------------------------------
2021-12-04 07:25:26 +00:00
const hasContainer =
globalSymbols.indexOf(IDENTIFIER_DISPATCHER_CONTAINER) > -1;
2020-08-25 22:11:26 +00:00
if (!hasContainer) {
global[IDENTIFIER_DISPATCHER_CONTAINER] = create();
}
const ret: {
2021-12-04 07:25:26 +00:00
instance: T;
setInstance: (value: T) => void;
2020-08-25 22:11:26 +00:00
} = {
instance: global[IDENTIFIER_DISPATCHER_CONTAINER],
setInstance: (value: T) => {
global[IDENTIFIER_DISPATCHER_CONTAINER] = value;
2021-12-04 07:25:26 +00:00
},
};
2020-08-25 22:11:26 +00:00
// define the singleton API
// ------------------------
2021-12-04 07:25:26 +00:00
Object.defineProperty(ret, "instance", {
2020-08-25 22:11:26 +00:00
get: function () {
return global[IDENTIFIER_DISPATCHER_CONTAINER];
2021-12-04 07:25:26 +00:00
},
2020-08-25 22:11:26 +00:00
});
// ensure the API is never changed
// -------------------------------
Object.freeze(ret);
return ret;
2021-12-04 07:25:26 +00:00
}