Last active
June 13, 2017 17:52
-
-
Save dadamssg/ac5639eb222e81dbf13afe652b8476e5 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
class Container { | |
constructor () { | |
this._definitions = {} | |
} | |
register (id, func, factory = false) { | |
if (typeof func !== 'function') { | |
throw new Error('Invalid service function.') | |
} | |
this._definitions[id] = { | |
func, | |
factory | |
} | |
} | |
prime (id, instance) { | |
this._definitions[id] = {instance} | |
} | |
get (id) { | |
const definition = this._definitions[id] | |
if (!definition) { | |
throw new Error(`No service definition: ${id}`) | |
} | |
if (definition.factory) { | |
return definition.func(this) | |
} | |
if (!definition.instance) { | |
definition.instance = definition.func(this) | |
} | |
return definition.instance | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment