Skip to content

Instantly share code, notes, and snippets.

@supasympa
Last active August 22, 2018 21:11
Show Gist options
  • Save supasympa/6ebd7fc6c238d3350709e1f67ae06b40 to your computer and use it in GitHub Desktop.
Save supasympa/6ebd7fc6c238d3350709e1f67ae06b40 to your computer and use it in GitHub Desktop.
Javascript IOC
/*
IOC ...
*/
const Bar = () => {
return {
hello: 'world'
};
};
const baz = (s) => {
return s.split("").reverse().join("");
};
const Container = (initialState) => {
const mem = {};
if(initialState){
Object.keys(initialState).forEach(key => {
mem[Symbol.for(key)] = initialState[key];
});
}
return {
register: (key, val) => mem[Symbol.for(key)] = val,
get: (key) => mem[Symbol.for(key)]
}
};
const container = Container({
foo: 'Foo',
bar: Bar(),
baz
});
const control = (
myFoo = container.get('foo'),
myBar = container.get('bar'),
myBaz = container.get('baz'),
) => {
return {
go(){
console.log(myFoo);
console.log(myBar);
console.log(myBaz(`somestring`));
}
};
};
const controlA = control();
controlA.go(); /* >
Foo
{ hello: 'world' }
gnirtsemos
*/
container.register('foo', 'Foo bar baz .. changed!');
container.register('baz', (s) => s.toUpperCase());
const controlB = control();
controlB.go();/*
Foo bar baz .. changed!
{ hello: 'world' }
SOMESTRING at myBaz(`somestring`)
*/
controlA.go();/* >
Foo
{ hello: 'world' }
gnirtsemos
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment