Skip to content

Instantly share code, notes, and snippets.

@bradparker
Created November 17, 2015 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradparker/964a2056b9f490325f05 to your computer and use it in GitHub Desktop.
Save bradparker/964a2056b9f490325f05 to your computer and use it in GitHub Desktop.
Smoosh two object's methods together
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