alia
Version:
Alias To Go
26 lines (25 loc) • 698 B
JavaScript
const registry = new Map();
const stack = new Set();
export function inject(token) {
const instance = registry.get(token);
if (instance) {
return instance;
}
if (stack.has(token)) {
const chain = [...stack].map((t) => t.name).join(' -> ');
stack.clear();
throw new Error(`Circular dependency in ${token.name}: ${chain} -> ${token.name}`);
}
stack.add(token);
const newInstance = new token();
stack.delete(token);
return provide(token, newInstance);
}
export function provide(token, instance) {
registry.set(token, instance);
return instance;
}
export function clearProviders() {
registry.clear();
stack.clear();
}