Home > Back-end >  Is there a method to evaluate N variables in N functions (vector) using JavaScript
Is there a method to evaluate N variables in N functions (vector) using JavaScript

Time:04-20

I have a vector of function F=(F1,F2…Fn) and F1 contains n variables (x1,x2...,xn), Same for F2 to Fn. I want to evaluate F by a vector x, How can write it using JavaScript?

F and x are vectors.

F=[[F1],[F2]…[Fn]];
x=[[x1],[x2]…[xn]]; 

I want to return

y = [[F1(x)],[F1(x)]…[Fn(x)]]

For example:

F=[[x1^2 - x2 -1], [x1 - x2^2   1]]
x=[[1], [2]]

CodePudding user response:

It's hard to tell exactly what you're looking for from your question, but I thought I would give a shot at giving you an answer.

The first thing I do, is describe an array where each element is a function. Then I create an array of values to pass to each function. Finally, I use the Array .map method to pass the values into each function and give the result in a results array.

const functions = [
  (x1, x2) => x1 ** 2 - x2 - 2,
  (x1, x2) => x1 -  x2 ** 2   1
];

const xVals = [1, 2];

const results = functions.map(fn => fn(...xVals));

console.log(results); //logs [-3, -2]

  • Related