mrkeyoor.com_
Sat 08 Aug 22:51 UTC
npmUtilsupdated 08 Aug 2026

math-expression-evaluator

math-expression-evaluator parses calculator-style text such as `2(3+4)`, `sin90`, `5C2`, and `Sigma(1,5,n)` without calling JavaScript eval. A stateful `Mexp` instance tokenizes the input, converts it to postfix notation, and evaluates it as a JavaScript number. It includes degree-based trigonometry, factorials, permutations, combinations, summation, products, implicit multiplication, and an extension API for custom constants and functions. It is a calculator grammar, not a general symbolic algebra system or spreadsheet engine.

Verdict

A useful compact parser for a calculator UI whose grammar matches its unusual choices. Do not use it for finance, exact computation, unrestricted server input, or any product where left-associative powers and degree-default trig would surprise users.

API stability4/5The public class remains centered on eval, lex, toPostfix, postfixEval, addToken, and the TOKEN_TYPES enum, and version 2 has received incremental releases from December 2022 through June 2025. The API is small enough to learn quickly, but some stability is accidental rather than contractual: there is no exports map, token objects expose numeric parser categories, and mutable math and token internals are part of normal configuration.
Docs2/5The README has a useful supported-symbol table and examples for Sigma, Pi, implicit parentheses, and the three-stage parse pipeline. It also omits the import in its main example, still documents Bower, calls a nonexistent lexed method in one extension sample, and says natural log of 2 is 0.3010 even though the source correctly uses Math.log. The shipped declarations are concise but do not explain errors, limits, or token construction.
Maintenance3/5Version 2.0.7 was published in June 2025 after a sequence of seven 2.x updates since late 2022, and the repository was pushed ten days after that release. It is neither archived nor disabled. GitHub reports 24 open issues and pull requests, while the build still lists old Mocha 2 and ESLint 6 development tooling, so maintenance exists but does not look intensive or heavily resourced.
Ecosystem3/5The package recorded 2,916,641 downloads for the measured week and has no runtime dependencies, making it easy to embed in existing JavaScript projects. Included TypeScript declarations cover the class and token shapes, and a prebuilt browser file is published. The surrounding ecosystem is thin: there are no official framework adapters, variable environments, formatting tools, or plugin packages, and most integration work uses the low-level token API.

Use it if

  • You need a small dependency-free calculator parser with implicit multiplication and parenthesis-free functions such as sin90
  • Your input needs built-in factorial, permutation, combination, Sigma, or Pi product notation
  • You want to add a few application-specific constants or numeric functions through a token table
  • All results can use JavaScript Number precision and expressions come from a controlled calculator-style UI
Skip it if

Setup reality

`npm install math-expression-evaluator` is the whole install: version 2.0.7 has no runtime dependencies, peer dependencies, native code, credentials, or configuration files, and it includes declarations under `dist/types`. The package entry is CommonJS and does not publish an exports map or module field, so default-import behavior depends on your TypeScript and bundler interop settings; `const Mexp = require('math-expression-evaluator')` matches the emitted entry exactly. Create an instance before calling `eval`. Trigonometric functions start in degree mode, which makes `sin90` equal 1 but makes radian-oriented formulas wrong until you set `mexp.math.isDegree = false`. Exponentiation is left-associative. The parser permits implicit multiplication and parenthesis-free function calls, conveniences that can make ambiguous user input harder to explain. Invalid syntax throws ordinary Error objects, so validate length and catch failures at the boundary. Custom tokens mutate the evaluator and remain available in later calls; use a dedicated, preconfigured instance rather than mixing user-defined token sets between tenants. Constants need both a token definition and a values object during evaluation. There are no built-in CPU guards, so impose expression-length, numeric-range, and Sigma or Pi bounds before evaluating untrusted text. Results use JavaScript floating-point arithmetic and are normalized to 15 decimal places internally, which is unsuitable for money or exact science work.

Patterns

Evaluate a basic arithmetic expressionevaluate-arithmetic

const Mexp = require('math-expression-evaluator');

const mexp = new Mexp();
const value = mexp.eval('2 + 3 * 4');
console.log(value); // 14

Invalid characters or grammar throw an Error. Catch it when the expression comes from user input.

Use implicit multiplicationuse-implicit-multiplication

const value = mexp.eval('2(3 + 4)');
console.log(value); // 14

Adjacent values and parentheses can imply multiplication. This is convenient for calculator input but differs from JavaScript syntax.

Evaluate trigonometry in degree modeevaluate-degree-trig

const value = mexp.eval('sin90 + cos(0)');
console.log(value); // 2

Degree mode is enabled on every new instance, and function parentheses are optional.

Switch trigonometry to radiansswitch-to-radians

mexp.math.isDegree = false;
const value = mexp.eval('sin(pi / 2)');
console.log(value); // 1

The mode is mutable instance state. Do not share one instance between callers that expect different angle units.

Evaluate powers with explicit groupingevaluate-powers

const squaredCube = mexp.eval('(2^3)^2'); // 64
const powerTower = mexp.eval('2^(3^2)'); // 512

Without parentheses, `2^3^2` is evaluated left to right and returns 64. Group power towers explicitly.

Use factorial, combination, and permutationevaluate-combinatorics

const factorial = mexp.eval('5!'); // 120
const combinations = mexp.eval('5C2'); // 10
const permutations = mexp.eval('5P2'); // 20

These operations use JavaScript Number and plain loops. Large inputs overflow or consume noticeable CPU.

Sum a sequence with Sigmasum-a-sequence

const total = mexp.eval('Sigma(1, 100, n)');
console.log(total); // 5050

Only `n` is the built-in sequence variable, and there is no iteration limit. Validate both bounds before evaluation.

Multiply a sequence with Pimultiply-a-sequence

const product = mexp.eval('Pi(1, 5, n)');
console.log(product); // 120

Pi with a capital P is the product function; lowercase pi is the mathematical constant. Tokens are case-sensitive.

Split lexing, postfix conversion, and evaluationreuse-parsed-expression

const lexed = mexp.lex('2 * (3 + 4)');
const postfix = mexp.toPostfix(lexed);
const value = mexp.postfixEval(postfix);
console.log(value); // 14

The method is named lex, not lexed as one README example states. Reusing postfix output avoids parsing the same fixed expression again.

Add a named numeric constantadd-custom-constant

const T = Mexp.TOKEN_TYPES;
mexp.addToken([{
  token: 'x',
  show: 'x',
  type: T.CONSTANT,
  value: 'x',
  precedence: 0,
}]);

const value = mexp.eval('2x + 1', undefined, { x: 3 });
console.log(value); // 7

Defining the token makes the name parseable; the third argument supplies its numeric value for that evaluation.

Add a custom unary functionadd-custom-function

const T = Mexp.TOKEN_TYPES;
mexp.addToken([{
  token: 'abs',
  show: 'abs',
  type: T.FUNCTION_WITH_ONE_ARG,
  value: Math.abs,
  precedence: 11,
}]);

console.log(mexp.eval('abs(-4)')); // 4

Added tokens persist on the evaluator instance. Register a fixed trusted set during startup, not from arbitrary user input.

Reject invalid calculator inputhandle-invalid-expression

function calculate(input) {
  if (input.length > 200) throw new Error('Expression too long');
  try {
    const value = mexp.eval(input);
    if (!Number.isFinite(value)) throw new Error('Non-finite result');
    return value;
  } catch {
    throw new Error('Invalid expression');
  }
}

Length is only a first guard. Also restrict numeric and Sigma or Pi bounds when evaluating input from untrusted callers.

Alternatives

PackageRegistryPick it when
mathjsnpmYou need units, matrices, fractions, big numbers, complex values, typed functions, and a much broader expression language
expr-eval-forknpmYou want a maintained expression-parser fork with variables, exports-map support, and published security fixes
@cortex-js/compute-enginenpmYou need symbolic mathematics, LaTeX input, exact forms, or expression trees rather than calculator-only numeric output