Last active
November 1, 2015 16:47
-
-
Save gmmorris/7f7c9ec305926e72e8c8 to your computer and use it in GitHub Desktop.
An example of a composer factory for my How to Grok a Higher Order Class article
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 FactorySentinal = Symbol('ClassFactory'); | |
export function isFactory(SupposedFactory) { | |
return SupposedFactory && SupposedFactory[FactorySentinal]; | |
} | |
export default function(methodComposer) { | |
return ClassToCompose => { | |
const proto = ClassToCompose.prototype; | |
function factory() { | |
const instance = new ClassToCompose(...arguments); | |
for (const prop of Object.getOwnPropertyNames(proto)) { | |
const method = proto[prop]; | |
const {configurable, writable} = Object.getOwnPropertyDescriptor(proto, prop); | |
if (method instanceof Function && | |
// we can't change non configurable or writable methods | |
configurable && writable && | |
// touching the constructor won't help us here, as we're modifying an existing instance | |
method !== ClassToCompose) { | |
instance[prop] = methodComposer(proto[prop], prop); | |
} | |
} | |
return instance; | |
} | |
factory[FactorySentinal] = true; | |
return factory; | |
}; | |
} |
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
import factoryComposer from './composers_factory'; | |
// This is the base class we wish to compose | |
class ComposableBaseClass { | |
// ... methods | |
} | |
// This is the functionality we wish to add to our class - we want to wrap each Method | |
// on the composable class in our little 'verbose' function which 'console.log's the name | |
// of the method being called. | |
function verbosify(func, funcName) { | |
return function() { | |
// ... add verbosity to this function's execution | |
return func.apply(this, arguments); | |
}; | |
} | |
/** | |
* Factory Example | |
*/ | |
// create verbosified factory creator - this would only be done once per function, so it would only be used once for the 'verbosify' function in your codebase | |
const createVerbosifiedFactory = factoryComposer(verbosify); | |
// create verbosified factory of the composable class - this would be used per class you wish to attach the verbose beahviour to | |
const vebosifiedComposedClassFactory = createVerbosifiedFactory(ComposableBaseClass); | |
// usage of factory every time you want a verbose instance of ComposableBaseClass | |
let myVerboseInstance = vebosifiedComposedClassFactory(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment