1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00
lens/src/common/utils/singleton.ts
Panu Horsmalahti 1477bb8274 Enforce semicolons in eslint
Signed-off-by: Panu Horsmalahti <phorsmalahti@mirantis.com>
2020-11-19 16:35:04 +02:00

28 lines
762 B
TypeScript

/**
* Narrowing class instances to the one.
* Use "private" or "protected" modifier for constructor (when overriding) to disallow "new" usage.
*
* @example
* const usersStore: UsersStore = UsersStore.getInstance();
*/
type Constructor<T = {}> = new (...args: any[]) => T;
class Singleton {
private static instances = new WeakMap<object, Singleton>();
// todo: improve types inferring
static getInstance<T>(...args: ConstructorParameters<Constructor<T>>): T {
if (!Singleton.instances.has(this)) {
Singleton.instances.set(this, Reflect.construct(this, args));
}
return Singleton.instances.get(this) as T;
}
static resetInstance() {
Singleton.instances.delete(this);
}
}
export { Singleton };
export default Singleton;