I have an unusual situation where I need to dynamically generate a class prototype then have a reflection tool (which can't be changed) walk the prototype and find all the methods. If I could hard code the methods, the class definition would look something like this:
class Calculator {
constructor(name) { this.name = name; }
}
class AdditionCalculator extends Calculator {
constructor(name) { super(name); }
add(left, right) { console.log(this.name + (left + right)); }
}
class SubtractCalculator extends AdditionCalculator {
constructor(name) { super(name); }
subtract(left, right) { console.log(this.name + (left - right)); }
}
However, I can't hard code the methods/inheritance as I need a large number of combinations of methods that are data driven: For example, I need a Calculator with no math methods, a Calculator with Add() only, Calculator with Subtract() only, Calculator with Add() and Subtract(), and many more combos.
Is there any way to do this with JavaScript (I assume with prototypes)?
For reference, here's the reflection tool that finds the methods:
function getMethods(obj:object, deep:number = Infinity):Array<string> {
let props:string[] = new Array<string>()
type keyType = keyof typeof obj
while (
(obj = Object.getPrototypeOf(obj)) && // walk-up the prototype chain
Object.getPrototypeOf(obj) && // not the the Object prototype methods (hasOwnProperty, etc...)
deep !== 0
) {
const propsAtCurrentDepth:string[] = Object.getOwnPropertyNames(obj)
.concat(Object.getOwnPropertySymbols(obj).map(s => s.toString()))
.sort()
.filter(
(p:string, i:number, arr:string[]) =>
typeof obj[<keyType>p] === 'function' && // only the methods
p !== 'constructor' && // not the constructor
(i == 0 || p !== arr[i - 1]) && // not overriding in this prototype
props.indexOf(p) === -1 // not overridden in a child
)
props = props.concat(propsAtCurrentDepth)
deep--
}
return props
}
For example: getMethods(new SubtractCalculator("name")); would return ["add", "subtract"]
One could choose a composition and inheritance based approach where a factory-function creates a named subclass/subtype on-the-fly.
As for the OP's use case, one in addition, applies function-based mixin-composition in order to augment the subclass constructor's prototype. Thus, everything is covered by inheritance (the prototype chain), either directly via the subclass constructor's augmented prototype or via the further linked prototype of the base class.
The advantage of the entire approach comes with not having to write too much boilerplate (and repeating) code if it comes to the dynamic (or add-hoc) creation of Calculator
based subclasses.
// - factory function which implements dynamic sub-classing (or sub-typing).
// - the below implementation is generic, thus it not only allows/supports
// the creation of named subclasses derived from the additionally provided
// base class, but it also supports function-based mixin-composition at
// both instance and class level.
function createNamedSubclassWithMixedInBehavior(
className = 'UnnamedType' , baseClass = Object, mixinConfig = {}
) {
const {
compose: instanceLevelMixins = [],
inherit: classLevelMixins = [],
} = mixinConfig;
const subClass = ({
[className]: class extends baseClass {
constructor(...args) {
super(...args);
instanceLevelMixins
.forEach(behavior => behavior.call(this));
}
},
})[className];
classLevelMixins
.forEach(behavior => behavior.call(subClass.prototype));
return subClass;
}
// function-based mixins, each implementing a unique trait/behavior.
function withNegation() {
this.negate = function negate (right) {
return (-1 * right);
}
}
function withAddition() {
this.add = function add (left, right) {
return (left + right);
}
}
function withSubtraction() {
this.subtract = function subtract (left, right) {
return (left - right);
}
}
// base `Calculator` class.
class Calculator {
constructor(name) {
this.name = name;
}
}
// a lookup based configuration of operator mixins.
const operatorMixins = {
negation: [withNegation],
addition: [withAddition],
subtraction: [withSubtraction],
negation_addition: [withNegation, withAddition],
negation_subtraction: [withNegation, withSubtraction],
addition_subtraction: [withAddition, withSubtraction],
negation_addition_subtraction: [withNegation, withAddition, withSubtraction],
};
// helpers for calculator instance logs.
function getConstructorName(value) {
return Object.getPrototypeOf(value).constructor.name;
}
function getBaseConstructorName(value) {
return Object.getPrototypeOf(Object.getPrototypeOf(value)).constructor.name;
}
// creation, access and logging of `Calculator` subclasses.
[
['negation', 'NegationType', 'negationOnly'],
['addition', 'AdditionType', 'addOnly'],
['subtraction', 'SubtractionType', 'subtractOnly'],
['negation_addition', 'NegationAdditionType', 'negateAndAdd'],
['negation_subtraction', 'NegationSubtractionType', 'negateAndSubtract'],
['addition_subtraction', 'AdditionSubtractionType', 'addAndSubtract'],
['negation_addition_subtraction', 'NegationAdditionSubtractionType', 'negateAndAddAndSubtract'],
]
.map(([operatorFlag, className, instanceName]) => [
createNamedSubclassWithMixedInBehavior(
className, Calculator, { inherit: operatorMixins[operatorFlag] }
),
instanceName,
])
.forEach(([CalculatorSubClass, instanceName]) => {
const calculatorSubType = new CalculatorSubClass(instanceName);
console.log({
instanceName: calculatorSubType.name,
className: getConstructorName(calculatorSubType),
baseClassName: getBaseConstructorName(calculatorSubType),
negate: calculatorSubType.negate,
add: calculatorSubType.add,
subtract: calculatorSubType.subtract,
"negate(-7)": calculatorSubType?.negate?.(-7),
"add(1,14)": calculatorSubType?.add?.(1, 14),
"subtract(19,10)": calculatorSubType?.subtract?.(19, 10),
});
});
.as-console-wrapper { min-height: 100%!important; top: 0; }