Last active
December 12, 2022 10:38
-
-
Save joyqi/0c71083f0aabffe3af4ce00ca416d80b to your computer and use it in GitHub Desktop.
Implement a simple singleton function in TypeScript
This file contains hidden or 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
const instances = new WeakMap(); | |
// Create a singleton instance. | |
export function singleton<T>(fn: () => T): () => T { | |
return () => { | |
let instance = instances.get(fn); | |
if (!instance) { | |
instance = fn(); | |
instances.set(fn, instance); | |
} | |
return instance; | |
}; | |
} | |
// Usage | |
// get the redis client | |
export const getRedis = singleton( | |
() => new IORedis() | |
); | |
const redis = getRedis(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment