I’d like to create some kind of factory to automate the process of creating JS classes. The factory should loop through an object that contains classes names and their respective parameters. The following simplified code sample hopefully demonstrates what I mean:
// function for dependency injection
addNumbers = (numbers) => {
let result = 0;
numbers.forEach((number) => {
result = result + number;
})
console.log(`\nThe result is ${result}`);
}
// class without parameters
class Log {
constructor() {
console.log ('My only job is to log this text!\n');
}
}
// class with parameters
class Greeting {
constructor(params) {
this.sayHello(params);
}
sayHello(params) {
for (const [key, name] of Object.entries(params)) {
console.log(`Hallo ${name}, nice to meet you!`);
}
}
}
// class with parameters
// and dependency injection
class Addition {
constructor(params) {
this.injectedMethod = params['dependency'];
this.injectedMethod(params['numbers']);
}
}
classParams = {
Log: '',
Greeting: {
name1: 'Alice',
name2: 'Bob'
},
Addition: {
numbers: [1, 2, 3, 4, 5],
dependency: addNumbers
}
}
// Here comes the critical part:
// I'd like to have a loop that replaces the
// following code and iterates through
// classParams, creating the classes with
// their respective parameters
new Log();
new Greeting(classParams['Greeting']);
new Addition(classParams['Addition']);
I tried something like
for (const [object, params] of Object.entries(classParams)) {
new [object](params);
}
.. but that won’t work because inside the loop I don’t get the class as an object but only as a string. I tried some things I found online, but the best I could achive was having no errors – but having no working classes either.
What am I getting wrong?
>Solution :
You can put all the classes into an object and use bracket notation to access classes by name using it.
const addNumbers=e=>{let o=0;e.forEach(e=>{o+=e}),console.log(`
The result is ${o}`)};class Log{constructor(){console.log("My only job is to log this text!\n")}}class Greeting{constructor(e){this.sayHello(e)}sayHello(e){for(let[o,t]of Object.entries(e))console.log(`Hallo ${t}, nice to meet you!`)}}class Addition{constructor(e){this.injectedMethod=e.dependency,this.injectedMethod(e.numbers)}}const classParams={Log:"",Greeting:{name1:"Alice",name2:"Bob"},Addition:{numbers:[1,2,3,4,5],dependency:addNumbers}};
const classes = {Log, Greeting, Addition};
for (const [k, v] of Object.entries(classParams)) {
new classes[k](v);
}