Here's a javascript puzzle not strictly related to SMP, I hope it is not too off topic.
I'm working on a nested objects system, where each object is an item in an array property of a container object. The methods of the container object execute the method with the same name in the nested objects. This is done by calling another method - the forward() method in the code below - so the container constructor function has the following structure:
function Container(){
this.items = [obj1, obj2, obj3...];
this.method1 = (...args) => {this.forward('method1', ...args)};
this.method2 = (...args) => {this.forward('method2', ...args)};
this.method3 = (...args) => {this.forward('method3', ...args)};
...
this.methodN = (...args) => {this.forward('methodN', ...args)};
this.forward = (method, ...args) => {
this.items.forEach((item) => {if (method in item) item[method](...args)});
}
}
Since the methods from 1 to N have the same pattern I thought I could make them perfectly alike and thus simply reference the forward() method for all. What I need is to ditch the "method" argument in the forward() method and retrieve it by code from the caller method's name. But it turns out it is harder than I thought. Ideally I would like to write something like:
function Container(){
this.items = [obj1, obj2, obj3...];
this.method1 = this.forward;
this.method2 = this.forward;
this.method3 = this.forward;
...
this.methodN = this.forward;
this.forward = ( ...args) => {
this.items.forEach((item) => {
let method = //...code to retrieve the caller*** method's name
if (method in item) item[method](...args)});
}
}
//***if this kind of code did work like I mean, the container's method would not be a caller anymore, just a reference.
It looks like such a typical scenario for javascript that I'm confident there must be a way, but everything I tried failed. Do you have any suggestion?