Created
April 7, 2020 15:27
-
-
Save jsmanifest/1598cd25f529a61aa77b31a7ca6014d7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import parseFunction from 'parse-function' | |
const app = parseFunction({ | |
ecmaVersion: 2017, | |
}) | |
class DIC { | |
constructor() { | |
this.dependencies = {} | |
this.factories = {} | |
} | |
register(name, dependency) { | |
this.dependencies[name] = dependency | |
} | |
factory(name, factory) { | |
this.factories[name] = factory | |
} | |
get(name) { | |
if (!this.dependencies[name]) { | |
const factory = this.factories[name] | |
if (factory) { | |
this.dependencies[name] = this.inject(factory) | |
} else { | |
throw new Error('No module found for: ' + name) | |
} | |
} | |
return this.dependencies[name] | |
} | |
inject(factory) { | |
const fnArgs = app.parse(factory).args.map((arg) => this.get(arg)) | |
return new factory(...fnArgs) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment