Created
November 17, 2015 08:01
-
-
Save bradparker/964a2056b9f490325f05 to your computer and use it in GitHub Desktop.
Smoosh two object's methods together
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
const { keys, assign } = Object | |
const concern = { | |
doSideEffectyThing () { | |
this.property1 = 'Hip, hip!' | |
} | |
} | |
const instance = { | |
someProp: 'Foo', | |
doSideEffectyThing (name) { | |
this.property2 = `Horay! ${ name }` | |
} | |
} | |
const isFunc = (candidate) => (candidate instanceof Function) | |
const methodCompose = (concern, instance) => { | |
return keys(concern).reduce((newInstance, prop) => { | |
if (!isFunc(concern[prop])) { | |
throw new Error('methodCompose() composes only methods') | |
} | |
if (!isFunc(instance[prop])) return newInstance | |
newInstance[prop] = (...args) => { | |
concern[prop].apply(newInstance, args) | |
instance[prop].apply(newInstance, args) | |
} | |
return newInstance | |
}, assign({}, instance)) | |
} | |
const another = methodCompose(concern, instance) | |
another.doSideEffectyThing('Me') | |
// [object Object] { | |
// doSideEffectyThing () { | |
// ... | |
// }, | |
// property1: "Hip, hip!", | |
// property2: "Horay! Me", | |
// someProp: "Foo" | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment