Last active
March 30, 2020 12:04
-
-
Save Stradivario/1bb94d6cd58749e4b94f8ed5c59ae71f to your computer and use it in GitHub Desktop.
Dependency Injection in 24 lines of code using Typescript
This file contains 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
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