Skip to content

Instantly share code, notes, and snippets.

@Stradivario
Last active March 30, 2020 12:04
Show Gist options
  • Save Stradivario/1bb94d6cd58749e4b94f8ed5c59ae71f to your computer and use it in GitHub Desktop.
Save Stradivario/1bb94d6cd58749e4b94f8ed5c59ae71f to your computer and use it in GitHub Desktop.
Dependency Injection in 24 lines of code using Typescript
type ObjectType<T> = new (...args: unknown[]) => T;
const C = new Map();
const ascii = (a: string) => a.charCodeAt(0);
const toHashKey = <T>(c: ObjectType<T>) =>
`${c}`
.split('')
.map(ascii)
.join('')
.substring(0, 50);
export const get = <T>(c: ObjectType<T>): T => C.get(toHashKey(c));
export const has = <T>(c: ObjectType<T>): boolean => !!C.has(toHashKey(c));
export const set = <T>(c: ObjectType<T>, hash = toHashKey(c)): T =>
C.set(hash, new c()).get(hash);
export const Inject = <T>(clazz: ObjectType<T>): PropertyDecorator => (
target,
name: string
) =>
Object.defineProperty(target, name, {
get: () => set(clazz)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment