'Change the argument of a function that is inside another function
This are my tasks:

As you can see, they all have "same" logic. So I wanted use function like this ->
const task71=(x)=>Math.tan(2*x+x*x);
const main=(x,dX,xEnd)=>{
while(x<=xEnd)
{
task71(x); //this part I wanna change, so it will work for task72,task73...
x+=dX;
console.log(`Y=${task71(x)}\nX=${x}`);
}
}
This works only for task71(x),but I have task72(x),task73(x),etc. What do I need to change in
main(x,dx,xEnd) function to make it work for another functions?
I tried use task71(x) as argument, but in this way the function only works with the initial value of x.
Perhaps this question is stupid, sorry, I recently started learning programming.
Solution 1:[1]
You can load all your taks into an object, and then execute each task in your main:
const tasks = {
71: (x)=>Math.tan(2*x+x*x),
73: (x)=>Math.pow(x+1, 2),
}
const main=(x,dX,xEnd)=>{
while(x<=xEnd)
{
for(let id in tasks)
{
let y = tasks[id](x); //this part I wanna change, so it will work for task72,task73...
console.log(`task${id}:\nY=${y}\nX=${x}`);
}
x+=dX;
}
}
main(2.40,0.20,7.60);
Alternatively you can pass the task function to the main:
const tasks = {
71: (x)=>Math.tan(2*x+x*x),
73: (x)=>Math.pow(x+1, 2),
}
const main=(x,dX,xEnd, taskId)=>{
while(x<=xEnd)
{
let y = tasks[taskId](x); //this part I wanna change, so it will work for task72,task73...
x+=dX;
console.log(`task${taskId}:\nY=${y}\nX=${x}`);
}
}
for(let id in tasks)
{
main(2.40,0.20,7.60, id);
}
Solution 2:[2]
I think you want something like this:
const taskmap = {
task71: (x)=>Math.tan(2*x+x*x);
// etcetera
};
And then:
const main=(x,dX,xEnd)=>{
func_count = 71;
while(x<=xEnd)
{
var fn = taskmap['task'+func_count];
fn(x);
x+=dX;
console.log(`Y=${fn(x)}\nX=${x}`);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vanowm |
| Solution 2 | Blunt Jackson |
