1.0.2 • Published 5 years ago

@shyjs/calculator v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
5 years ago

中文文档

calculator

A mathematical expression parser for Javascript.

  • Works in Wechat miniProgram
  • Supports IE9+
  • Supports AMD/CommonJS
  • Supports custom operators

You can use the util to parse a mathematical expression into an Reverse Polish Notation or evaluate it.For example,when you parse 1+2*3,you will get the expression + * 3 2 1 and the result 7.

Installation

Direct download

Download the script here and include it:

<script src="/dist/calculator.min.js"></script>
<!-- or -->
<script src="/dist/calculator.js"></script>

Package Managers

NPM

$ npm install @iboxer/calculator --save

AMD

require(['./dist/calculator.js'], function(Calculator) {
  var calculator = new Calculator()
  calculator.parse("1+2+3")
})

Basic Usage

Instance

new Calculator(options)

var calculator = new Calculator();

options

handleError: Error handler.For more details, please click hereclick here

operators: Custom operators.For more details, please click hereclick here

Parse

var result = calculator.parse("1+2*3");
console.log(result);

You will get the result:

npm.io

  • value: The result of evaluating the expression
  • notation: The Reverse Polish Notation of parsing the expression

So you can get the result by result.value and get the notation by result.notation.

The util supports parsing mathematical operator(like +,-,*,/) and functions,Currently it supports by default the following mathematical operators:

OperatorTypePrecedenceDescription
+prefix3positive sign
-prefix3negative sign
+infix2addition
-infix2subtraction
*infix4multiplication
/infix4division
\|infix4Mod
%postfix6percentage
(,)prefix,postfix0parentheses
!postfix6factorial
^infix4exponentiation
//infix4radical expression
logfunc0logarithm
absfunc0get absolute value
sin,tan,cosfunc0trigonometric function
,infix1parameter separator of a function

API

You can also define custom operators and functions by using the API definedOperators(Object|Array).For example, you may define an operator || to get the quotient and an function ca to get the area of a circle:

calculator.definedOperators({
  token: "||",
  type: "infix",
  func: function(a, b) {
    return Math.floor(a / b);
  },
  weight: 4
});
calculator.definedOperators({
  token: "ca",
  type: "func",
  func: function(r) {
    return Math.PI * r * r;
  }
});

console.log("ca(5) = ", calculator.parse('ca(5)').value); // ca(5) =  78.53981633974483
console.log("10 || 3 + 2 = ", calculator.parse('10 || 3 + 2').value); // 10 || 3 + 2 = 5
ParamTypeRequiredDescription
tokenStringYesname of the operator,can not be(, )or,
funcFunctionYesthe handle function
typeStringNotype of the operator,just can be prefix,'infix',postfix and func,default func
weightNumberNothe precedence of the operator,default 0
rtolBooleanNois it a right-combination operator?,default undefined

The same operator can be infix and prefix ,like the operator +,but infix and postfix should be mutually exclusive The API can pass in an object or an array of objects to define a set of operators at the same time

Errors

When parse a invalid expression, you will get an error.In order to customize error handling, exceptions will not be thrown directly.Instead,you will get the result like:

{
  code: 1004,
  message: "Opening parenthesis is more than closing parenthesis",
  pos: 20,
  token: "/"
}
keydescription
codeerror code
messagedescription
posthe error position in the expression
tokencurrent operator
and get a warning on console like:

![](./images/error.png)

By default, the error object is returned as a result, and you can define a custom error-handler by passing  `handleError` for the instance:

```javascript
var calculator = new Calculator({
  handleError: function(err) {
    if(err.code === 1006)
      return {
        value: Infinity
      }
  }
});

Here are all the error types:

| code | description|
|:----:|--------|
|1001|Contains undefined operators|
|1002|Syntax error|
|1003|Missing a opening parenthesis after a function|
|1004|Opening parenthesis is more than closing parenthesis|
|1005|Closing parenthesis is more than opening parenthesis|
|1006|The divisor cannot be zero|
|1007|The base number of logarithmic operations must be greater than 0 and not equal to 1|
|1008|The factorial base must be a non-negative integer|


## Demos

[Demos](./test/index.html)