Aviv Roth
JavaScript: String to Function call
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.
Recent Comments
- JPEREZGIL on REST calls in .NET (C#) over SSL (HTTPS)
- Reivaj810 on REST calls in .NET (C#) over SSL (HTTPS)
- Juancastein on Installing SharePoint 2013 on Windows Server 2012 R2 Preview
- Juancastein on Installing SharePoint 2013 on Windows Server 2012 R2 Preview
- Arjen Holterman on REST calls in .NET (C#) over SSL (HTTPS)
Categories