Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
A JavaScript Formula Parser
fparser provides a Formula class that parses strings containing mathematical formulas (e.g. x*sin(PI*x/2)
) into an evaluationable object.
One can then provide values for all unknown variables / functions and evaluate a numeric value from the formula.
For an example application, see https://fparser.alexi.ch/.
Parses a mathematical formula from a string. Known expressions:
-1*(sin(2^x)/(PI*x))*cos(x))
Include directly in your web page:
<!-- Within a web page: Load the fparser library: -->
<script src="dist/fparser.js"></script>
<script>const f = new Formula('x+3');</script>
Install it from npmjs.org:
# Install it using npm:
$ npm install --save fparser
Then use as ES6 module (recommended):
import Formula from 'fparser';
or use it as UMD module:
const Formula = require('fparser');
... and finally use it:
// 1. Create a Formula object instance by passing a formula string:
const fObj = new Formula('2^x');
// 2. evaluate the formula, delivering a value object for each unknown entity:
let result = fObj.evaluate({ x: 3 }); // result = 8
// or deliver multiple value objects to return multiple results:
let results = fObj.evaluate([{ x: 2 }, { x: 4 }, { x: 8 }]); // results = [4,16,256]
// You can also directly evaluate a value if you only need a one-shot result:
let result = Formula.calc('2^x', { x: 3 }); // result = 8
let results = Formula.calc('2^x', [{ x: 2 }, { x: 4 }, { x: 8 }]); // results = [4,16,256]
const fObj = new Formula('a*x^2 + b*x + c');
// Just pass a value object containing a value for each unknown variable:
let result = fObj.evaluate({ a: 2, b: -1, c: 3, x: 3 }); // result = 18
Instead of single-char variables (like 2x+y
), you can also use named variables in brackets:
const fObj = new Formula('2*[var1] + sin([var2]+PI)');
// Just pass a value object containing a value for each named variable:
let result = fObj.evaluate({ var1: 5, var2: 0.7 });
The reason for the bracket syntax is the support of shortcut multiplication of single vars, e.g. 2xy
is a shorthand for 2*x*y
. As the parser cannot decide if xy
means "the variable named xy", or
calc x*y`, we had to introduce the
bracket syntax.
Named variables in brackets can also describe an object property path:
const fObj = new Formula('2*[var1.propertyA] + 3*[var2.propertyB.propertyC]');
// Just pass a value object containing a value for each named variable:
let result = fObj.evaluate({ var1: { propertyA: 3 }, var2: { propertyB: { propertyC: 9 } } });
This even works for array values: Instead of the property name, use a 0-based index in an array:
// var2.propertyB is an array, so we can use an index for the 3rd entry of propertyB:
const fObj = new Formula('2*[var1.propertyA] + 3*[var2.propertyB.2]');
let result = fObj.evaluate({ var1: { propertyA: 3 }, var2: { propertyB: [2, 4, 6] } });
const fObj = new Formula('sin(inverse(x))');
//Define the function(s) on the Formula object, then use it multiple times:
fObj.inverse = (value) => 1/value;
let results = fObj.evaluate({x: 1,x:2,x:3});
// Or pass it in the value object, and OVERRIDE an existing function:
let result = fObj.evaluate({
x: 2/Math.PI,
inverse: (value) => (-1*value)
});
If defined in the value object AND on the formula object, the Value object has the precedence
Functions also support the object path syntax:
// in an evaluate() value object:
const fObj = new Formula('sin(lib.inverse(x))');
const res = fObj.evaluate({
lib: { inverse: (value) => 1/value }
});
// or set it on the Formula instance:
const fObj2 = new Formula('sin(lib.inverse(x))');
fObj2.lib = { inverse: (value) => 1/value };
const res2 = fObj.evaluate();
You can instantiate a Formula object without formula, and set it later, and even re-use the existing object:
const fObj = new Formula();
// ...
fObj.setFormula('2*x^2 + 5*x + 3');
let res = fObj.evaluate({ x: 3 });
// ...
fObj.setFormula('x*y');
res = fObj.evaluate({ x: 2, y: 4 });
To avoid re-calculation of already evaluated results, the formula parser object supports memoization: it stores already evaluated results for given expression parameters.
Example:
const fObj = new Formula('x * y', { memoization: true });
let res1 = fObj.evaluate({ x: 2, y: 3 }); // 6, evaluated by calculating x*y
let res2 = fObj.evaluate({ x: 2, y: 3 }); // 6, from memory
You can enable / disable memoization on the object:
const fObj = new Formula('x * y');
let res1 = fObj.evaluate({ x: 2, y: 3 }); // 6, evaluated by calculating x*y
fObj.enableMemoization();
let res2 = fObj.evaluate({ x: 2, y: 3 }); // 6, evaluated by calculating x*y
let res3 = fObj.evaluate({ x: 2, y: 3 }); // 6, from memory
The Formula
class blacklists its internal functions like evaluate
, parse
etc. You cannot create a formula that calls an internal Formula
function:
// Internal functions cannot be used in formulas:
const fObj = new Formula('evaluate(x)');
fObj.evaluate({ x: 5 }); // throws an Error
// This also counts for function aliases / references to internal functions:
const fObj = new Formula('ex(x)');
fObj.ex = fObj.evaluate;
fObj.evaluate({ x: 5 }); // still throws an Error: ex is an alias of evaluate
The Formula
object keeps a function reference of all blacklisted functions in the Formula.functionBlacklist
array.
You can get a list of all blacklisted functions:
let blacklistNames = Formula.functionBlacklist.map((f) => f.name));
Or you can check if a specific function is in the blacklist:
fObj = new Formula('x * y');
// fObj.evaluate is a Function pointer to an internal, blacklisted function:
Formula.functionBlacklist.includes(fObj.evaluate);
If you want to provide your own function for a blacklisted internal function,
provide it with the evaluate
function:
fObj = new Formula('evaluate(x * y)');
fObj.evaluate({ x: 1, y: 2, evaluate: (x, y) => x + y });
Now, evaluate
in your formula uses your own version of this function.
// Get all used variables in the order of their appereance:
const f4 = new Formula('x*sin(PI*y) + y / (2-x*[var1]) + [var2]');
console.log(f4.getVariables()); // ['x','y','var1','var2']
After parsing, get the formula string as parsed:
// Get all used variables in the order of their appereance:
const f = new Formula('x * ( y + 9 )');
console.log(f.getExpressionString()); // 'x * (y + 9)'
This is a long-wanted "migrate to typescript and modernize build infrastrucure" release. It introduces some few breaking changes, which hopefully are simple to adapt in existing code, or does not affect end users at all (I hope).
dist/fparser.umd.js
instead of dist/fparser.js
: If you need the UMD version, use dist/fparser.umd.js
instead of dist/fparser.js
.VariableExpression
class now needs Formula instance in constructor. This should not affect any end-user, but I did not test all edge cases.obj.fn(3*[obj.value])
)3*[obj1.property1.innerProperty]
), thanks to SamStonehouse-z*t
), the parser got confused.This release is a complete re-vamp, see below. it should be completely backward compatible to the 1.x versions, but I did not test all edge cases.
getExpressionString()
function to get a formatted string from the formula2x + [var1]
)Licensed under the MIT license, see LICENSE file.
FAQs
A Math Formula parser library for JavaScript
The npm package fparser receives a total of 2,320 weekly downloads. As such, fparser popularity was classified as popular.
We found that fparser demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.