Last active
August 22, 2018 21:11
-
-
Save supasympa/6ebd7fc6c238d3350709e1f67ae06b40 to your computer and use it in GitHub Desktop.
Javascript IOC
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
/* | |
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