Skip to content

Instantly share code, notes, and snippets.

@joyqi
Last active December 12, 2022 10:38
Show Gist options
  • Save joyqi/0c71083f0aabffe3af4ce00ca416d80b to your computer and use it in GitHub Desktop.
Save joyqi/0c71083f0aabffe3af4ce00ca416d80b to your computer and use it in GitHub Desktop.
Implement a simple singleton function in TypeScript
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