Math.js compile() Function
Last Updated :
03 Jan, 2023
The Math.js is an extensive library with mathematical functions that work on JavaScript and Node.js. The additional feature of this library is that it provides a flexible expression parser that supports symbolic computation. It is quite powerful and easy to use since it comes with many built-in functions and offers data types such as fractions, complex numbers, matrices, and units.
Math.js Compile function is used for parsing and compiling an expression. The Math.js Compile function returns an object with the compiled expression which is of the function Math.js evaluate([scope]).
Syntax:
math.compile(expression)
or
math.compile([expression A, expression B, expression C, ...])
Parameters: This method accepts only one parameter which is mentioned and described below:
- Expression: This parameter is used to specify the expression which has to be compiled.
Return Value: This method returns an object with the compiled expression.
Example 1: This example shows the basic use of the Math.js compile() function.
HTML
< script type = "text/javascript" src = "math.js" >
</ script >
< script type = "text/javascript" >
// Defining a constant and calling
// the compile function
const a = math.compile('pow(4, 3)')
// Displaying the output
document.writeln(" Result = "
+ a.evaluate());
</ script >
|
Output:
Result = 64
Example 2: This example explains the above approach.
HTML
< script type = "text/javascript" src = "math.js" >
</ script >
< script type = "text/javascript" >
// Defining a scope
let testScope = { a: 30, b: 5 }
// Calling the compile function
const result = math.compile('a/b')
// Displaying the result
document.writeln(" Result = "
+ result.evaluate(testScope));
</ script >
|
Output:
Result = 6
Example 3: This example shows the basic use of the Math.js compile() function.
HTML
< script type = "text/javascript" src = "math.js" >
</ script >
< script type = "text/javascript" >
// Defining a node and calling
// the compile function
const testNode = math.compile(
['a = 12', 'b = 2', 'a / b'])
// Displaying the result
document.writeln(" Result = "
+ testNode[2].evaluate());
</ script >
|
Output:
Result = 6
Note: This will not work in normal JavaScript because it requires the Math.js library to be installed.
Share your thoughts in the comments
Please Login to comment...