Skip to content

Instantly share code, notes, and snippets.

@gmmorris
Created November 1, 2015 16:46
Show Gist options
  • Save gmmorris/6cb891d40184ffa52a41 to your computer and use it in GitHub Desktop.
Save gmmorris/6cb891d40184ffa52a41 to your computer and use it in GitHub Desktop.
An example of a All Method Constructor Composer for my How to Grok a Higher Order Class article
export default function(methodComposer) {
return ClassToCompose => {
class ComposedClass extends ClassToCompose {
constructor() {
super(...arguments);
}
}
const baseProto = ClassToCompose.prototype;
for (const prop of Object.getOwnPropertyNames(baseProto)) {
const method = baseProto[prop];
const {configurable, writable} = Object.getOwnPropertyDescriptor(baseProto, prop);
if (method instanceof Function &&
// we can't change non configurable or writable methods
configurable && writable &&
// touching the constructor won't work here
method !== ClassToCompose) {
ComposedClass.prototype[prop] = methodComposer(baseProto[prop], prop);
}
}
return ComposedClass;
};
}
import allMethodComposer from './extend_all_method_composer';
/**
* We'll use the same ComposableBaseClass class and verbosify function from before
*/
/**
* Composite 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 createVerbosifiedClass = allMethodComposer(verbosify);
// create verbosified factory of the composable class - this would be used per class you wish to attach the verbose beahviour to
const VerbosifiedComposedClass = createVerbosifiedClass(ComposableBaseClass);
// usage of factory every time you want a verbose instance of ComposableBaseClass
myVerboseInstance = new VerbosifiedComposedClass();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment