Ice101781
Ice101781

Reputation: 105

How can I write a JavaScript function that will call another function passed as a parameter?

I'm trying to write a JavaScript function that will integrate functions using Simpson's Rule. I fully understand the math behind Simpson's Rule, but I'm unsure of how to write a function that will integrate another function. Here's the code I'd like to implement:

integrate = function(leftBound, rightBound, numSubIntervals, expression) {

    var a = leftBound,
        b = rightBound,
        n = numSubIntervals,
        myFunc = expression;

    /*implementation of simpson's rule..*/

    return result;
}

My issue is that I don't know how to pass a mathematical expression (the function to be integrated) as a parameter without doing something like passing it as a string and using eval(), which is not something I want to do. I also don't want to use any third-party libraries. I want to write the function using vanilla JavaScript only. What am I missing here - is there an obvious solution to this?

Upvotes: 0

Views: 112

Answers (2)

Peter O.
Peter O.

Reputation: 32888

Functions themselves can be arguments to other functions. For example:

integrate(0,5,10, function(x){
 return x*x;
})

This example takes a function that takes a given X and squares it. Within integrate, you would call this function for given intervals of x to integrate this function using Simpson's rule.


Within integrate, the syntax for calling a function passed to it is:

var point = expression(x);

Where x is the value passed to the function named expression, and point is the return value of expression.

Upvotes: 2

olivarra1
olivarra1

Reputation: 3409

Here's my answer-version of my comment. You can pass the function as parameter and then call it from inside.

integrate = function(leftBound, rightBound, numSubIntervals, expression) {

    var a = leftBound,
        b = rightBound,
        n = numSubIntervals,
        myFunc = expression;

    /*implementation of simpson's rule..*/
    result = (b-a)/6 * (expression(a) + 4*f* ... );

    return result;
}

var toIntegrate = function(x){
  return 2*x*x*x - 3*x*x + 2*x - 1;
}

integrate(0, 10, 10, toIntegrate);

Upvotes: 2

Related Questions