UNPKG

singleton-proxy

Version:

A lightweight TypeScript singleton implementation using Proxy pattern

18 lines (17 loc) 517 B
export function singleton(target) { let instance = null; return new Proxy(target, { construct(target, args) { if (!instance) { instance = new target(...args); } return instance; }, apply(target, thisArg, args) { if (!instance) { instance = target.apply(thisArg, args); } return instance !== null && instance !== void 0 ? instance : target.apply(thisArg, args); } }); }