@nu-art/commando
Version:
40 lines (39 loc) • 1.48 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MergeClass = MergeClass;
exports.CreateMergedInstance = CreateMergedInstance;
/**
* Function to merge multiple classes into a single class.
* @template T - An array of constructors.
* @param {...T} plugins - The constructors to merge.
* @returns {Constructor<MergeTypes<T>>} - A new constructor that merges all the provided constructors.
*/
function MergeClass(...plugins) {
class SuperClass {
/**
* Constructs an instance of SuperClass, merging properties from all plugins.
* @param {...any[]} args - The arguments to pass to the constructors.
*/
constructor(...args) {
plugins.forEach(plugin => {
Object.getOwnPropertyNames(plugin.prototype).forEach(name => {
const prop = Object.getOwnPropertyDescriptor(plugin.prototype, name);
if (prop) {
Object.defineProperty(this, name, prop);
}
});
});
}
}
return SuperClass;
}
/**
* Function to create an instance of a class that merges multiple classes.
* @template T - An array of constructors.
* @param {...T} plugins - The constructors to merge.
* @returns {MergeTypes<T>} - An instance of the merged class.
*/
function CreateMergedInstance(...plugins) {
const SuperClass = MergeClass(...plugins);
return new SuperClass();
}