So I discovered this neat JavaScript hack: what do you do if you have a string that is the name of a function, that you want to convert to the function call itself?

Pretty simple actually. It turns out that:

object['method']()

 

…evaluates to:

object.method()

 

Why/when is this useful? Well, I found it using the regression-js package:

Suppose you have some constants, for the different regression types:

const RegressionTypes = {
    NONE: null,
    LINEAR: 'linear',
    EXPONENTIAL: 'exponential',
    LOGARITHMIC: 'logarithmic',
    POWER: 'power',
    POLYNOMIAL: 'polynomial',
};

 

I originally had code in a switch statement to tell me when to call which function:

function getRegression(points, regressionType) {
    if (!points || !regressionType || regressionType === RegressionTypes.NONE) {
        return null;
    }

    switch (regressionType) {
        case RegressionTypes.LINEAR:
            return regression.linear(points).points;
        case RegressionTypes.EXPONENTIAL:
            return regression.exponential(points).points;
        case RegressionTypes.LOGARITHMIC:
            return regression.logarithmic(points).points;
        // ...
        default:
            return null;
    }
}

 

With this little hack, I can reduce the switch statement to one line:

function getRegression(points, regressionType) {
    if (!points || !regressionType || regressionType === RegressionTypes.NONE) {
        return null;
    }

    // evaluates the constant's value to the function to call in the 'regression' package
    // e.g. if regressionType === RegressionTypes.LINEAR, the below evaluates to
    // 'return regression.linear(points).points;'
    return regression[regressionType](points).points;
}

 

Pretty neat, in my opinion.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Set your Twitter account name in your settings to use the TwitterBar Section.