josdejong/mathjs
55.9
Adequate · 1 October 2026
60.5k
lines of production code
JavaScript
primary language
2
measurements over time
What this system is
This system is the math.js library, a comprehensive JavaScript tool for parsing, evaluating, and manipulating mathematical expressions and data structures. It provides a wide range of capabilities including arithmetic, algebra, calculus, linear algebra, and unit conversions, supporting diverse numeric types like BigNumbers, Fractions, and Complex numbers. The library features a modular, factory-based architecture that enables tree-shaking and secure, isolated instances, along with interactive CLI and browser-based interfaces for expression evaluation.
How it got here
2013–2018 — modular factory architecture and ES module migration
72 changes.
The project underwent a comprehensive architectural overhaul, restructuring the codebase around a modular factory pattern to enable granular imports and efficient tree-shaking. This period saw the migration to ES modules, the introduction of native BigInt support, and the expansion of capabilities across algebra, linear algebra, and unit handling. Additionally, significant improvements were made to the expression engine, documentation, and developer tooling to enhance usability and performance.
2019 — test coverage expansion and build optimization
32 changes.
This period focused on significantly expanding unit test coverage across the library's core types, algebra, and expression parsing subsystems. Concurrently, the project refactored its build infrastructure to support tree-shaking and introduced dedicated entry points for improved modularity and configuration safety.
2020–2026 — TypeScript support and new math functions
13 changes.
This period focused on introducing comprehensive TypeScript type definitions and validating them with dedicated tests. It also expanded the library's capabilities by adding new functions for eigenvalue decomposition, ODE solving, signal processing, and fraction manipulation, each accompanied by thorough unit testing.
Features
Add binary, octal, and hexadecimal formatting functions
New string formatting functions \bin\, \oct\, and \hex\ are introduced to convert numbers into their binary, octal, and hexadecimal string representations, respectively. These functions support optional \wordSize\ parameters to format values as signed two's complement integers with size suffixes (e.g., \0xffi8\). The existing \format\ function is also updated to recognize \bin\, \oct\, and \hex\ notations, allowing users to perform these conversions via the standard formatting API with consistent options like \precision\ and \wordSize\.
src/function/string · high confidence
Add code editor example using mathjs and CodeMirror
A new interactive code editor example has been added to the examples directory. It integrates the mathjs library with CodeMirror to provide syntax highlighting, autocompletion, and live evaluation of mathematical expressions, displaying results in a markdown-formatted panel alongside the editor.
_examples/code\editor · high confidence
Add embedded documentation for Construction category functions
This change introduces embedded documentation files for the Construction category, providing syntax, descriptions, and examples for functions including bigint, bignumber, boolean, complex, createUnit, fraction, index, matrix, number, sparse, splitUnit, string, and unit. These docs are now available for inline help and reference within the expression parser.
src/expression/embeddedDocs/construction · high confidence
Add erf and zeta special functions
The library now includes the error function (\erf\) and the Riemann Zeta function (\zeta\). The \erf\ function computes the error function for real numbers, arrays, and matrices using rational Chebyshev approximations. The \zeta\ function calculates the Riemann Zeta function for real numbers, complex numbers, and BigNumbers, utilizing Riemann's Functional equation for the calculation.
src/function/special · high confidence
Add linear system solvers for triangular and LU-decomposed matrices
New functions are now available to solve linear equation systems: \lsolve\ and \usolve\ perform forward and backward substitution on lower and upper triangular matrices respectively, while \lusolve\ solves general systems using LU decomposition. Additionally, \lsolveAll\ and \usolveAll\ have been added to find all possible solutions for systems with singular matrices, supporting both dense and sparse matrix inputs.
src/function/algebra/solver · high confidence
Add plain BigNumber arithmetic operations
The library now exposes plain functions for basic arithmetic (absolute value, addition, subtraction, multiplication, and division) on BigNumber instances, alongside a factory function to create them using decimal.js. This allows users to perform these operations without relying on the library's typed-function dispatcher.
src/plain/bignumber · high confidence
Added CSparse algebra functions for sparse matrix factorization
This location introduces a suite of JavaScript implementations of the CSparse library (from SuiteSparse) to support sparse matrix operations. The changes add core algorithms including approximate minimum degree ordering (csAmd), Cholesky factorization (csChol), LU factorization (csLu), and symbolic analysis (csSqr), along with supporting utilities for tree traversal, permutation, and pattern reachability. These functions enable advanced sparse linear algebra capabilities within the algebra module.
src/function/algebra/sparse · high confidence
Added documentation for erf and zeta special functions
Embedded documentation has been added for the \erf\ (error function) and \zeta\ (Riemann Zeta function) special functions. Users can now view syntax, descriptions, and usage examples for these functions within the application's help system, supporting the underlying implementation of these mathematical capabilities.
src/expression/embeddedDocs/function/special · high confidence
Added documentation for unit conversion functions
New embedded documentation entries have been added for the 'to' and 'toBest' functions within the Units category. The 'to' function allows users to change the unit of a value (e.g., converting inches to cm), while 'toBest' converts a value to the most appropriate display unit from a list or with specific options.
src/expression/embeddedDocs/function/units · high confidence
Added embedded documentation for config, import, and typed functions
New documentation entries have been added for the core \config\, \import\, and \typed\ functions. Users can now view syntax, descriptions, and usage examples for retrieving or changing configuration settings, importing functions or constants from objects, and creating typed functions with specific signatures directly within the embedded help system.
src/expression/embeddedDocs/core · high confidence
Added embedded documentation for utility functions
Embedded documentation has been added for a suite of utility functions in the Utils category, including type-checking functions (isInteger, isNaN, isNegative, isNumeric, isPositive, isZero, isPrime, isFinite, isBounded, hasNumericValue), type conversion (numeric, typeOf), formatting (bin, oct, hex, format), cloning (clone), and string interpolation (print).
src/expression/embeddedDocs/function/utils · high confidence
Added freqz and zpk2tf signal processing functions
Users can now compute the frequency response of digital filters using the new \freqz\ function, which accepts numerator and denominator coefficients and returns complex frequency response data. Additionally, the \zpk2tf\ function allows conversion of zero-pole-gain models into transfer function polynomial coefficients. Both functions are available in the Signal category and support arrays and matrices.
src/expression/embeddedDocs/function/signal, src/function/signal · high confidence
Added matrix and vector validation for linear solvers
A new \solveValidation\ utility has been introduced in the solver utils to validate matrix and column vector inputs for backward and forward substitution algorithms. This function ensures that the input matrix is square and that the dimensions of the column vector \b\ match the matrix rows, throwing a \RangeError\ on dimension mismatches. It handles various input types including dense matrices, sparse matrices, and plain arrays, converting them into a standardized dense column vector format for downstream processing.
src/function/algebra/solver/utils · high confidence
Added num and den helper functions for fractions
Users can now extract the numerator and denominator of a fraction using the new \num(x)\ and \den(x)\ functions. These functions work with Fraction and BigNumber inputs, automatically simplifying results to lowest terms and handling negative signs consistently (signs are stored in the numerator, so the denominator is always positive). They also support element-wise evaluation on arrays and matrices.
src/expression/embeddedDocs/function/fraction, src/function/fraction · high confidence
Added re, im, arg, and conj functions for complex numbers
Users can now extract specific components of complex numbers using the new \re\, \im\, \arg\, and \conj\ functions. These functions return the real part, imaginary part, argument (angle), and complex conjugate, respectively. They support scalar inputs (numbers, BigNumbers, Complex objects) as well as Arrays and Matrices, where the operation is applied element-wise.
src/function/complex · high confidence
Added solveODE function for numerical integration of ODEs
Users can now solve ordinary differential equations using the new \solveODE\ function in the Numeric category. This feature supports adaptive Runge-Kutta methods (RK23 and RK45) to numerically integrate forcing functions over a specified time span, returning the resulting time and state arrays. It accepts optional configuration for tolerance, step sizes, and iteration limits, and supports scalar or array initial values.
src/expression/embeddedDocs/function/numeric, src/function/numeric · high confidence
Added web worker example for asynchronous math evaluation
A new example demonstrating how to run math.js in a web worker to prevent UI freezing during heavy calculations. The example includes a \MathWorker\ class that sends expressions to a background worker via \postMessage\ and handles asynchronous responses, allowing users to evaluate expressions without blocking the main thread.
examples/browser/webworkers · high confidence
BigNumber function now supports word-size suffixes and unit conversion
The \math.bignumber()\ function has been enhanced to handle string inputs containing word-size suffixes (e.g., \0x10i8\ for 8-bit integers), allowing for explicit bit-width interpretation of hexadecimal, binary, and octal literals. Additionally, the function now correctly converts \Unit\ objects by preserving the unit while converting the value to a BigNumber, and it supports \bigint\ inputs directly.
src/type/bignumber/function · high confidence
Bitwise functions now support BigInt and optimized matrix operations
The bitwise functions (bitAnd, bitOr, bitXor, bitNot, leftShift, rightArithShift, rightLogShift) have been rewritten to support the JavaScript \bigint\ type in addition to numbers and BigNumbers. Matrix operations for these functions are now handled via a unified matrix algorithm suite, enabling optimized element-wise evaluation for DenseMatrix and SparseMatrix types. The implementation also includes a helper to convert array-scalar operations to matrix operations for consistent behavior.
src/function/bitwise · high confidence
Complex number type implementation
The \Complex\ type is now implemented in \src/type/complex/Complex.js\, providing a concrete class for complex numbers. This change introduces methods for JSON serialization (\toJSON\, \fromJSON\), polar coordinate conversion (\toPolar\, \fromPolar\), and string formatting with configurable precision. It also adds a \compare\ function for ordering complex numbers and ensures compatibility with the library's factory pattern and tree-shaking via \/\* \#\_\PURE\\_ \*/\ annotations.
src/type/complex · high confidence
Comprehensive embedded documentation for matrix functions
The embedded help system for the Matrix category has been populated with detailed documentation for a wide range of functions, including \column\, \concat\, \count\, \cross\, \ctranspose\, \det\, \diag\, \diff\, \dot\, \eigs\, \fft\, \filter\, \flatten\, \forEach\, \getMatrixDataType\, \identity\, \ifft\, \inv\, \kron\, \map\, \mapSlices\, \matrixFromColumns\, \matrixFromFunction\, \matrixFromRows\, \ones\, \partitionSelect\, \pinv\, \range\, \reshape\, \resize\, \rotate\, \rotationMatrix\, \row\, \size\, \sort\, \squeeze\, \subset\, \trace\, \transpose\, and \zeros\. Each entry provides the function name, category, syntax signatures, descriptions, usage examples, and related functions, ensuring users have immediate access to reference material within the application.
src/expression/embeddedDocs/function/matrix · high confidence
Embedded documentation added for relational and statistics functions
The embedded documentation system now includes reference entries for the full set of relational functions (compare, compareNatural, compareText, deepEqual, equal, equalText, larger, largerEq, smaller, smallerEq, unequal) and statistics functions (corr, cumsum, mad, max, mean, median, min, mode, prod, quantileSeq, std, sum, variance). Each entry provides the function name, category, syntax signatures, a description, usage examples, and related 'see also' links, enabling users to discover and understand these functions directly within the documentation interface.
src/expression/embeddedDocs/function/statistics · high confidence
Embedded documentation for constants, bitwise, and complex functions added
The embedded documentation system now includes reference entries for mathematical constants (such as Infinity, NaN, pi, and e), bitwise operations (including bitAnd, bitOr, bitXor, and shift functions), and complex number utilities (re, im, arg, and conj). These new documentation files provide syntax, descriptions, and usage examples for these specific functions and constants, making them discoverable and understandable within the application's help system.
src/expression/embeddedDocs/constants, src/expression/embeddedDocs/function/bitwise, src/expression/embeddedDocs/function/complex, src/expression/embeddedDocs/function/expression, src/expression/embeddedDocs/function/geometry · high confidence
Fraction function now supports bigint inputs
The \fraction\ function has been updated to accept \bigint\ arguments for both single-value and two-argument (numerator/denominator) constructors. This allows users to create fractions with arbitrary-precision integer values without losing precision or encountering overflow issues associated with standard JavaScript numbers.
src/type/fraction/function · high confidence
Initial release of TypeScript type definitions
This change introduces the complete TypeScript type definitions for the library, including the main declaration file (types/index.d.ts) and documentation (types/EXPLANATION.md). Users can now install the package and receive full type support for all functions, nodes, and configuration options, enabling better IDE autocomplete and compile-time checking without needing separate DefinitelyTyped packages.
types · high confidence
New CLI and REPL tools for interactive math.js usage
The \bin\ directory now includes \cli.js\ and \repl.js\, providing a command-line interface and a Read-Eval-Print Loop for interactive debugging. The CLI allows users to evaluate expressions, run script files, and process input streams, with options to control output formatting (LaTeX, string) and precision. It features auto-completion for variables, functions, and units, and improves startup performance by lazily loading the math.js library. The REPL provides a quick way to start an interactive session with the global math.js instance. Security measures are in place by disabling potentially dangerous functions like \import\ and \createUnit\ in the CLI environment.
bin · high confidence
New Unit class and physical constants implementation
The \src/type/unit\ location now contains the core \Unit\ class implementation and a dedicated module for physical constants. The \Unit.js\ file introduces a new constructor and parser for handling unit values, including support for prefixes and dimension tracking, while \physicalConstants.js\ defines constants like the speed of light and Planck constant using factory functions that respect the global \config.number\ setting (switching between standard numbers and BigNumbers). This change establishes the foundational data structures and logic for unit-aware calculations in the library.
src/type/unit · high confidence
New advanced examples for customizing math.js
Added a suite of new advanced examples demonstrating how to customize the math.js library. These include \custom\_loading.js\ for selective bundling, \custom\_datatype.js\ for defining new data types, \custom\_argument\_parsing.js\ for raw argument handling in the expression parser, \custom\_relational\_functions.js\ for overriding comparison logic, \custom\_scope\_objects.js\ for using custom scope maps, \custom\_evaluate\_using\_factories.js\ and \custom\_evaluate\_using\_import.js\ for building minimal evaluate instances, \more\_secure\_eval.js\ for disabling dangerous functions, \function\_transform.js\ for wrapping function behavior, \expression\_trees.js\ for parsing and transforming ASTs, and \convert\_fraction\_to\_bignumber.js\ for custom type conversions.
examples/advanced · high confidence
New algebraic functions: derivative, leafCount, polynomialRoot, rationalize, resolve, simplify, and more
The \src/function/algebra\ directory now contains a comprehensive suite of new algebraic functions. \derivative\ computes symbolic derivatives of expressions with optional simplification control. \simplify\, \simplifyConstant\, and \simplifyCore\ provide varying levels of expression simplification, including context-aware rules and constant folding. \rationalize\ transforms expressions into rational fractions and can return detailed coefficient data. \resolve\ substitutes variable nodes with scoped values, including cycle detection. \symbolicEqual\ checks if two expressions are algebraically equivalent by simplifying their difference. \polynomialRoot\ finds roots of linear, quadratic, and cubic polynomials. \leafCount\ counts leaf nodes in the parse tree. Matrix algebra functions \sylvester\ and \lyap\ solve the Sylvester and Continuous-time Lyapunov equations respectively. These functions are implemented using the factory pattern with explicit dependency injection.
src/function/algebra · high confidence
New and updated statistics functions with dimension support
The statistics module now includes new functions for correlation (\corr\), cumulative sum (\cumsum\), median absolute deviation (\mad\), and mode (\mode\). Existing functions such as \max\, \min\, \mean\, \std\, \sum\, \variance\, and \quantileSeq\ have been updated to support calculation along a specific dimension (axis) for matrices and multi-dimensional arrays. Additionally, \quantileSeq\ now supports calculating multiple quantiles at once or using evenly distributed steps.
src/function/statistics · high confidence
New bigint type and enhanced number parsing capabilities
This change introduces a new \bigint\ type, allowing users to create and convert values to JavaScript BigInts via \math.bigint()\, supporting conversions from numbers, strings, booleans, and matrices. Additionally, the \number\ type now supports parsing non-decimal literals (binary, octal, hexadecimal) with optional radix points and word-size suffixes (e.g., \0xffffi32\), enabling more flexible numeric input handling.
src/type · high confidence
New bitwise operations, constant factories, and tolerance-based comparison for BigNumbers
The BigNumber utility module now supports bitwise operations (AND, OR, NOT) for integer values, allowing users to perform low-level bit manipulation on large numbers. It introduces factory functions to lazily compute and memoize mathematical constants (e, phi, pi, tau) based on the current precision configuration. Additionally, a new \nearlyEqual\ function enables comparisons with configurable relative and absolute tolerances, addressing floating-point precision issues. The formatter has also been updated to support binary, octal, and hexadecimal notations with optional word-size suffixes for signed twos-complement formatting.
src/utils/bignumber · high confidence
New browser examples for math.js usage and visualization
Added a suite of new interactive HTML examples in the browser directory, including basic usage, angle configuration with custom trigonometric units, currency conversion via fixer.io, custom argument/decimal separators, function plotting with Plotly, and ODE-based simulations (Lorenz attractor and rocket trajectory optimization). The examples also demonstrate pretty-printing expressions using MathJax and generating styled HTML output, providing users with ready-to-run demonstrations of math.js features in a browser environment.
examples/browser · high confidence
New combinatorics functions: bellNumbers, catalan, composition, and stirlingS2
The combinatorics module now includes four new mathematical functions: \bellNumbers\ calculates the number of partitions of a set, \catalan\ computes Catalan numbers, \composition\ determines the number of compositions of n into k parts, and \stirlingS2\ calculates Stirling numbers of the second kind with caching for performance. These functions support both Number and BigNumber types and enforce input validation for non-negative integers.
src/function/combinatorics · high confidence
New configuration system and instance creation API
The core library now exposes a \create\ function that allows users to instantiate a math.js instance with custom configuration options, such as setting the default matrix type ('Matrix' or 'Array'), numeric type ('number', 'BigNumber', 'Fraction', or 'bigint'), precision, and tolerance settings. A new \config.js\ module defines default values for these settings, including \relTol\, \absTol\, \predictable\ mode, and \legacySubset\ behavior. This change enables users to tailor the library's behavior to their specific needs, such as using BigNumbers for high-precision arithmetic or enabling predictable output types for comparison functions.
src/core · high confidence
New example files for core math.js capabilities
Added a set of new example files in the \examples/\ directory demonstrating key math.js features, including algebraic simplification and derivatives, basic usage with constants and chained operations, BigNumbers for precision, fraction support, complex numbers, expression parsing and compilation, matrix manipulation (including sparse matrices), object handling, unit conversions, and serialization of math.js types to JSON.
examples · high confidence
New expression functions: compile, evaluate, help, and parser
This change introduces four new functions to the math.js expression API: \compile\, \evaluate\, \help\, and \parser\. The \compile\ function parses and compiles an expression into a reusable object with an \evaluate\ method, allowing for efficient repeated evaluation with different scopes. The \evaluate\ function directly parses, compiles, and evaluates an expression, supporting both single expressions and arrays/matrices of expressions, with optional scope support for variable read/write. The \help\ function retrieves embedded documentation for functions or data types, returning a Help object. The \parser\ function creates a new Parser instance that maintains a context of variables and functions, enabling stateful expression evaluation, variable definition, and function creation within that context. These functions are implemented as factory-created modules with dependencies on core parsing and typing utilities, and include \/\* \#\_\PURE\\_ \*/\ annotations to support tree-shaking.
src/expression/function · high confidence
New internal tooling for documentation, entry generation, and testing
The \tools\ directory now includes several new scripts to support the build and documentation process. \docgenerator.js\ parses JSDoc comments from function source files to automatically generate reference documentation in Markdown format. \entryGenerator.js\ uses Handlebars templates to create the ES module entry files and dependency graphs for the library. \approx.js\ provides internal assertion helpers (\approxEqual\, \approxDeepEqual\) that support epsilon-based comparisons for numbers, BigNumbers, and Complex types, used by the test suite. Additionally, \matrixmarket.js\ adds support for reading Matrix Market format files, and \update-authors.js\ automates the generation of the AUTHORS file from git history.
tools · high confidence
New matrix decomposition functions: LUP, QR, Schur, and Sparse LU
Users can now perform several new matrix decompositions via the \math\ library. The \lup\ function computes the LU decomposition with partial pivoting for dense matrices and arrays, returning the lower triangular matrix (L), upper triangular matrix (U), and permutation vector (P). The \qr\ function calculates the QR decomposition for dense and sparse matrices, returning orthogonal matrix Q and upper triangular matrix R. The \schur\ function performs a real Schur decomposition on square matrices, returning orthogonal matrix U and upper quasi-triangular matrix T. Additionally, the \slu\ function provides LU decomposition with full pivoting specifically for sparse matrices, allowing users to specify symbolic ordering and pivoting thresholds.
src/function/algebra/decomposition · high confidence
New matrix utility and linear algebra functions
This release adds a suite of new matrix functions to the library, including \column\ to extract specific columns, \concat\ to join matrices along a dimension, \count\ to count elements, \cross\ for 3D vector cross products, \ctranspose\ for complex conjugate transposes, \det\ using the Bareiss algorithm for improved precision, \diag\ to create or extract diagonal matrices, \diff\ to calculate element-wise differences with dimension support, \dot\ for vector dot products with sparse matrix optimization, \eigs\ for eigenvalue/eigenvector computation, \expm\ for matrix exponentials via Padé approximation, \fft\ supporting non-power-of-2 sizes via Chirp-Z transform, \filter\ and \forEach\ for array/matrix iteration, \flatten\ for reducing dimensions, and \getMatrixDataType\ to identify element types. These additions expand the library's capabilities for linear algebra, signal processing, and matrix manipulation.
src/function/matrix · high confidence
New plain number implementations for core math functions
This change introduces a new \src/plain/number\ module containing explicit JavaScript implementations for standard math operations (arithmetic, bitwise, combinations, constants, logical, probability, relational, trigonometry, and utils). These functions, such as \absNumber\, \logNumber\, \lgammaNumber\, and \modNumber\, are designed to handle native \number\ types directly, providing a foundation for the library's number handling. Notable additions include support for a base argument in the \log\ function, a corrected \mod\ implementation that handles negative numbers correctly, and the new \lgamma\ function for calculating the log-gamma of a number.
src/plain/number · high confidence
New probability functions and improved random generation
This update introduces several new probability functions: \bernoulli\ to calculate Bernoulli numbers, \kldivergence\ to compute the Kullback-Leibler divergence between distributions, \lgamma\ for the log-gamma function (supporting real and complex numbers), and \multinomial\ for multinomial coefficients. It also adds \combinationsWithRep\ for combinations with replacement and enhances \permutations\ with optional second-argument support. The \random\ and \randomInt\ functions now support generating matrices of random values, and \randomInt\ adds support for \bigint\ inputs. Additionally, \pickRandom\ now supports weighted selection and returning multiple items.
src/function/probability · high confidence
New unit conversion functions: to and toBest
Added two new functions for unit manipulation: \to\ allows converting a value to a specified target unit (supporting strings or Unit objects, with matrix broadcasting), and \toBest\ converts a unit to the most appropriate display unit, optionally constrained by a list of preferred units and an offset option.
src/function/unit · high confidence
New unit creation and splitting functions
Added three new functions to the unit type system: \createUnit\ allows users to define custom units with aliases, prefixes, and offsets; \splitUnit\ enables decomposing a unit into a sum of other units (e.g., splitting meters into feet and inches); and \unit\ provides a robust way to create unit instances from strings, numbers, or existing units, including support for dimensionless values and matrix mapping.
src/type/unit/function · high confidence
New utility functions for random matrix generation and seeded RNG
Added two new utility functions to the probability module: \randomMatrix\ for recursively generating random matrices based on a size array and a random function, and \createRng\ for creating a seeded pseudo-random number generator using the \seedrandom\ library. These utilities support more flexible random data generation and reproducible random sequences in probability calculations.
src/function/probability/util · high confidence
New utility functions for type checking, conversion, and cloning
This change introduces a suite of new utility functions in the math.js library to improve type safety, data handling, and numeric conversion. Users can now use \math.clone\ to create deep copies of objects, \math.hasNumericValue\ to detect numeric content in strings, and \math.typeOf\ to identify specific data types. Several existing type-checking functions (\isPositive\, \isNegative\, \isZero\, \isInteger\, \isNumeric\, \isNaN\, \isFinite\, \isBounded\) have been rewritten to support \bigint\ and \Fraction\ types, and \isPositive\/\isNegative\ now respect configuration tolerances (\relTol\, \absTol\). Additionally, \math.numeric\ provides explicit conversion between numeric types (number, BigNumber, bigint, Fraction).
src/function/utils · high confidence
New web server example demonstrating secure math evaluation in a worker process
Added a new example in \examples/advanced/web\_server\ that shows how to run math.js in a child process with limited execution time. The example includes a \server.js\ file using Express to expose a \/mathjs\ endpoint and a \math\_worker.js\ file that uses workerpool to evaluate expressions securely by disabling the \import\ function. Users can start the server and send GET requests with an \expr\ query parameter to get formatted math results, with a 10-second timeout to prevent long-running evaluations.
_examples/advanced/web\server · high confidence
Simplify function now accepts a context option to control simplification rules
The \simplify\ function in \src/function/algebra/simplify\ now supports a \context\ option, allowing users to customize which algebraic properties (such as commutativity, associativity, and triviality) are applied during simplification. This change introduces utility functions in \util.js\ to manage these contexts and adds wildcard helpers in \wildcards.js\ to identify constant and numeric nodes, enabling more precise control over how expressions are reduced.
src/function/algebra/simplify · high confidence
Support for polar coordinate objects in math.complex()
The math.complex() function now accepts object arguments using polar coordinates, specifically supporting properties named 'r' and 'phi' as well as 'abs' and 'arg'. This allows users to create complex numbers directly from magnitude and angle specifications, in addition to the existing support for rectangular coordinates ('re' and 'im').
src/type/complex/function · high confidence
Support for serializing Infinity, NaN, and BigInt in JSON
The JSON serialization and deserialization logic now handles special numeric values that standard JSON cannot represent. Users can now serialize \Infinity\, \-Infinity\, and \NaN\ numbers, as well as JavaScript \BigInt\ values, by using the new \replacer\ function. These values are stored in a custom format (e.g., \{ mathjs: 'number', value: 'Infinity' }\) and are correctly restored to their original types when parsed using the corresponding \reviver\ function.
src/json · high confidence
math.js v15.2.0 release with modular factory architecture
This release introduces math.js version 15.2.0 and restructures the library's internal architecture to use a factory-based module system. The codebase now exports individual function factories (e.g., \createAdd\, \createPi\) from dedicated entry points like \factoriesAny.js\ and \factoriesNumber.js\, allowing for more granular imports and tree-shaking. Constants such as \pi\, \tau\, \e\, and \phi\ are now implemented as factories that respect the \config.number\ setting, enabling them to return \BigNumber\ instances when configured. The library also adds support for \nullish\ coalescing, \bigint\ types, and new functions like \isFinite\, \isBounded\, and \toBest\. The default instance is now created via a central \create\ function that aggregates all factories, replacing the previous nested index structure.
src · high confidence
Architecture
Refactored core function infrastructure into modular factory-based components
The core function handling logic has been restructured into distinct, modular files: \config.js\ now manages instance configuration and validation, \import.js\ handles the dynamic importing and merging of functions and factories, and \typed.js\ implements the typed-function dispatcher with custom type definitions and conversions. This change decouples the creation of classes and functions from the core, enabling better tree-shaking, lazy loading, and dependency resolution within a math.js instance.
src/core/function · high confidence
Behavioural changes
Arithmetic functions rewritten with factory pattern and expanded type support
The arithmetic functions in src/function/arithmetic (including abs, add, ceil, floor, fix, gcd, lcm, and others) have been refactored to use a factory-based architecture, enabling better dependency injection and tree-shaking via \/\* \#\_\PURE\\_ \*/\ markers. This change significantly expands type support: functions now natively handle \bigint\, \Unit\ (with precision arguments for rounding functions), and \Fraction\ types, alongside existing support for \BigNumber\ and \Complex\. Matrix operations are now handled via a dedicated \matrixAlgorithmSuite\ for optimized element-wise and structural operations, and rounding functions (\ceil\, \floor\, \fix\) include tolerance-based logic to mitigate round-off errors.
src/function/arithmetic · high confidence
BigNumber type now respects dynamic configuration changes
The BigNumber type implementation has been refactored to listen for configuration updates, specifically precision changes. Previously, the BigNumber class was created with static config values; now, it registers a listener on the 'config' event to automatically apply new precision settings when they change, ensuring consistent behavior across the application without requiring manual re-initialization.
src/type/bignumber · high confidence
Consolidated embedded documentation structure
The embedded documentation system has been refactored from a factory function within a regular object into a centralized module (\embeddedDocs.js\) that aggregates documentation from individual, modular files. This change organizes documentation for constants, construction methods, and functions (algebra, arithmetic, bitwise, combinatorics, complex, expression, geometry, logical, matrix, probability, relational, set, and signal) into separate source files, improving maintainability and clarity for users browsing the documentation source.
src/expression/embeddedDocs · high confidence
Embedded documentation for arithmetic and trigonometry functions migrated to src
The embedded documentation for arithmetic and trigonometry functions has been moved from the \lib\ directory to \src/expression/embeddedDocs/function\. This change reorganizes the documentation source files for functions such as \abs\, \add\, \sin\, \cos\, and \pow\, ensuring they are located alongside the source code rather than in the compiled output directory.
src/expression/embeddedDocs/function/arithmetic · high confidence
Expression engine refactored with new Parser class and embedded documentation
The expression evaluation system has been restructured to use a new \Parser\ class that maintains its own persistent scope for variables and functions, allowing stateful evaluation across multiple expressions. The \Help\ class now evaluates documentation examples in an isolated scope to prevent configuration changes from affecting the global state. Additionally, the engine now includes embedded documentation for logical operators (and, or, xor, not, nullish) and supports new syntax features such as the nullish coalescing operator (\??\) and optional chaining (\?.\), with updated operator precedence rules.
src/expression · high confidence
Expression nodes refactored into ES modules with optional chaining support
The expression node classes (such as AccessorNode, ArrayNode, and FunctionNode) have been rewritten as ES modules using the factory pattern and marked with \/\* \#\_\PURE\\_ \*/\ to enable tree-shaking in bundlers like webpack. This change introduces support for optional chaining (e.g., \a?.b\), which allows safe property access that returns \undefined\ instead of throwing an error when the base object is null or undefined. Additionally, the nodes now include JSON serialization support (\toJSON\/\fromJSON\) and updated LaTeX/HTML string representations.
src/expression/node · high confidence
Expression transforms introduce one-based indexing and lazy evaluation
This change adds expression transform functions for matrix and logical operations (such as \row\, \column\, \index\, \and\, \or\, \nullish\, \filter\, \map\, and \forEach\). For users, this means that indexing in functions like \row\ and \column\ is now one-based (converting user input to zero-based internally), while dimension arguments in statistical functions like \sum\, \mean\, and \variance\ are converted from one-based to zero-based. Additionally, logical operators (\and\, \or\) and the \nullish\ operator now support lazy evaluation, and functions like \filter\ and \map\ can now accept inline expressions (e.g., \filter(\[3, -2, 5\], x \> 0)\).
src/expression/transform · high confidence
Fraction type now uses factory pattern with tree-shaking support
The Fraction type implementation has been refactored to use the internal factory pattern, wrapping the external 'fraction.js' library. This change adds specific type metadata (such as \isFraction\ and \type\) to the Fraction prototype and implements \toJSON\ and \fromJSON\ methods for serialization. Additionally, the factory function is marked with \/\* \#\_\PURE\\_ \*/\ to enable better tree-shaking in bundlers like webpack.
src/type/fraction · high confidence
Geometry functions rewritten with ES6 modules and expanded capabilities
The \distance\ and \intersect\ functions in \src/function/geometry\ have been completely rewritten as new ES6 modules. The \distance\ function now supports N-dimensional point-to-point calculations, point-to-line distances in 2D and 3D, and pairwise distances for sets of points, replacing the previous limited implementation. The \intersect\ function has been refactored to handle line-line intersections in 2D and 3D, as well as line-plane intersections in 3D, with improved handling of matrix inputs and null returns for non-intersecting cases. Both functions now use the factory pattern with explicit dependencies and include \/\* \#\_\PURE\\_ \*/\ annotations for better tree-shaking support.
src/function/geometry · high confidence
Improved error messages for statistics functions
A new utility function \improveErrorMessage\ has been added to the statistics module to provide more descriptive error messages when calculations fail. This enhancement ensures that users receive clearer feedback, including the specific function name (e.g., \max\) and argument details (type and value), when errors such as unexpected types or complex number operations occur, rather than seeing generic internal errors.
src/function/statistics/utils · high confidence
Introduce lazy-loaded Chain API for method chaining
The Chain type now supports lazy loading, meaning that math.js methods are only resolved when they are actually invoked on a chain instance rather than at initialization. This change improves startup performance and reduces memory usage by deferring the loading of method implementations until they are needed, while preserving the existing fluent interface for chaining operations like \.add()\ and \.done()\.
src/type/chain · high confidence
Introduction of custom error classes and secure property access utilities
The library now provides dedicated error types—ArgumentsError, DimensionError, and IndexError—to deliver clearer, structured error messages when function arguments or array indices are invalid. Additionally, a new security layer in customs.js enforces safe property access, preventing prototype pollution and unauthorized method invocation when reading or writing object properties, while supporting classes like ObjectWrappingMap and PartitionedMap ensure these safeguards are applied consistently across internal data structures.
src/utils · high confidence
Matrix types refactored to use the factory pattern
The matrix implementation classes (DenseMatrix, SparseMatrix, ImmutableDenseMatrix, Matrix, Index, Range, Spa, FibonacciHeap) and ResultSet have been converted to use the new factory-based dependency injection system. This change replaces the previous class-based structure with factory functions that explicitly declare their dependencies (such as 'Matrix', 'config', 'typed', 'FibonacciHeap'), enabling better modularity, tree-shaking, and dependency resolution within the library.
src/type/matrix · high confidence
New entry points for tree-shaking and readonly configuration
The library now provides dedicated entry points (\mainAny.js\, \mainNumber.js\, \allFactoriesAny.js\, \allFactoriesNumber.js\) designed to improve tree-shaking by separating factory collections and generated function lists. A new \configReadonly.js\ entry point exposes a configuration function that prevents global state mutation, encouraging users to create isolated math instances instead. Additionally, utility type-checking functions (e.g., \isNumber\, \isMatrix\) are now exported via a dedicated \typeChecks.js\ entry point.
src/entry · high confidence
New optimized algorithms for sparse and dense matrix element-wise operations
This change introduces a comprehensive set of new internal algorithms (matAlgo01 through matAlgo13) in the matrix utilities to handle element-wise operations between Dense and Sparse matrices, Sparse and Sparse matrices, and matrices with scalars. These algorithms optimize performance by iterating only over non-zero elements where possible and correctly handling data type inference, while also adding a new \broadcast\ utility to support broadcasting rules for matrices of different sizes.
src/type/matrix/utils · high confidence
New utility functions for expression transformation and callback handling
This change introduces several new utility modules in the expression transformation layer to support internal logic for scope management, dimension indexing, and callback adaptation. Specifically, it adds \compileInlineExpression\ to handle compiling and evaluating inline expressions with variable scoping, \dimToZeroBase\ and \lastDimToZeroBase\ to manage one-based to zero-based dimension conversions, \errorTransform\ to adjust error indices for user-facing messages, and \transformCallback\ to adapt callback functions based on the number of input arrays and expected arguments. These utilities provide the foundational helpers for the expression engine's transformation pipeline.
src/expression/transform/utils · high confidence
Refactored access and assign utilities to use factory pattern
The \access\ and \assign\ utility functions in \src/expression/node/utils\ have been restructured to use a factory pattern (\accessFactory\ and \assignFactory\). This change decouples these operations from global state by requiring dependencies like \subset\, \matrix\, and \errorTransform\ to be passed in explicitly. For users, this ensures that object property access, array subset retrieval, and assignment operations are handled more consistently and safely, with improved error transformation and support for various data types including matrices, strings, and objects.
src/expression/node/utils · high confidence
Refactored logical functions to ES6 modules with new nullish coalescing support
The logical functions (and, or, xor, not, nullish) have been rewritten as ES6 modules using the factory pattern, enabling better tree-shaking via \/\* \#\_\PURE\\_ \*/\ markers. This change introduces a new \nullish\ function that implements the nullish coalescing operator (??) behavior, returning the right-hand operand only when the left is null or undefined. The existing logical operators now support \bigint\ types alongside numbers, BigNumbers, Complex numbers, and Units, and their matrix implementations have been reorganized to use specific matrix algorithm utilities for improved performance and clarity.
src/function/logical · high confidence
Refactored matrix creation and indexing functions into modular factory components
The matrix creation and indexing logic in \src/type/matrix/function\ has been restructured into distinct, modular factory files (\index.js\, \matrix.js\, \sparse.js\). This change introduces \/\* \#\_\PURE\\_ \*/\ annotations to these functions to enable better tree-shaking in bundlers like webpack. Specifically, the \math.index\ function now supports indexing with arrays of booleans, the \math.matrix\ function explicitly handles dense and sparse storage formats via a unified factory, and the \math.sparse\ function is isolated for sparse matrix creation. These changes improve code maintainability and bundle size without altering the public API behavior.
src/type/matrix/function · high confidence
Relational functions rewritten as factory-based modules with bigint and tolerance support
The relational functions in \src/function/relational\ (including \compare\, \equal\, \larger\, \smaller\, \unequal\, \deepEqual\, \compareNatural\, \compareText\, and \equalText\) have been refactored from legacy implementations into a new factory-based architecture. This change introduces native support for JavaScript \bigint\ types across comparison operations, ensures that floating-point comparisons respect the configured \relTol\ and \absTol\ settings for near-equality checks, and adds robust handling for \null\ and \undefined\ values in equality checks. The new implementation also improves matrix broadcasting support and integrates unit comparison logic, providing a consistent and extensible foundation for all relational operations.
src/function/relational · high confidence
Set functions migrated to ES6 modules with tree-shaking support
The set operation functions (such as setCartesian, setDifference, setDistinct, setIntersect, setIsSubset, setMultiplicity, setPowerset, setSize, setSymDifference, and setUnion) have been refactored from CommonJS to ES6 import/export syntax. This change enables better tree-shaking in bundlers like webpack, allowing unused set functions to be excluded from the final bundle size. The underlying logic and API for these functions remain unchanged.
src/function/set · high confidence
Standardized embedded documentation for probability and combinatorics functions
The embedded documentation for the Probability and Combinatorics categories has been converted to a new, consistent format. This change updates the help content for functions including bernoulli, combinations, combinationsWithRep, distribution, factorial, gamma, kldivergence, lgamma, multinomial, permutations, pickRandom, random, and randomInt, as well as combinatorics functions like bellNumbers, catalan, composition, and stirlingS2. Users will see standardized syntax definitions, descriptions, and examples in the function reference, ensuring that documentation for these mathematical operations is uniform and easier to navigate.
src/expression/embeddedDocs/function/probability · high confidence
Trigonometry functions now support Units and Complex numbers
The trigonometry functions in \src/function/trigonometry\ have been updated to handle \Unit\ inputs (such as degrees) and \Complex\ numbers. Each function now uses a typed dispatcher to route inputs to the appropriate implementation: standard JavaScript math functions for numbers, library methods for Complex and BigNumber types, and a new \trigUnit\ helper that converts angle units to their numeric values before calculation. This allows users to pass units directly to functions like \sin\, \cos\, and \tan\ without manual conversion.
src/function/trigonometry · high confidence
Updated documentation for Set functions
The embedded documentation for the Set category functions (setCartesian, setDifference, setDistinct, setIntersect, setIsSubset, setMultiplicity, setPowerset, setSize, setSymDifference, and setUnion) has been updated. The changes clarify that multi-dimensional arrays are converted to single-dimension arrays before the operation and provide updated examples for each function.
src/expression/embeddedDocs/function/set · high confidence
Updated embedded documentation for algebra functions
The embedded documentation for the algebra category has been refreshed and standardized. This includes new documentation entries for \leafCount\, \polynomialRoot\, and \symbolicEqual\, as well as updated docs for existing functions like \derivative\, \simplify\, \resolve\, and the linear algebra solvers (\lsolve\, \usolve\, \lusolve\, etc.). The documentation now consistently uses the \.evaluate()\ method in examples (replacing the older \.eval()\), and the \resolve\ function's documentation explicitly notes that it may throw a \ReferenceError\ on reference loops.
src/expression/embeddedDocs/function/algebra · high confidence
Fixes
Support for complex and real symmetric eigenvalue decomposition
The \eigs\ function now handles matrices with complex entries and real symmetric matrices, which previously may have failed or produced incorrect results. This change introduces dedicated algorithms (\complexEigs\ and \realSymmetric\) to correctly compute eigenvalues and eigenvectors for these matrix types, including handling of defective matrices and numerical stability improvements through balancing and Hessenberg reduction.
src/function/matrix/eigs · high confidence
Test coverage
Add Node.js integration tests for library entry points and configuration; Add benchmark suite using tinybench; Added comprehensive TypeScript type tests; Added test coverage for CLI, sparse algebra, and matrix multiplication; Added test to verify tree-shaking effectiveness; Added tests for generated code entry points and dependency injection; Added unit tests for BigNumber type and function; Added unit tests for Complex, complex function, and ResultSet types; Added unit tests for JSON serialization and deserialization; Added unit tests for \to\ and \toBest\ functions; Added unit tests for algebra and set functions; Added unit tests for approx, constants, error classes, and sparse matrix decomposition; Added unit tests for core configuration, import, and type-checking logic; Added unit tests for erf and Riemann Zeta special functions; Added unit tests for expression functions and nullish coalescing support; Added unit tests for expression node classes; Added unit tests for fraction numerator and denominator helpers; Added unit tests for geometry distance and intersect functions; Added unit tests for inverse trigonometric functions; Added unit tests for lastDimToZeroBase utility; Added unit tests for linear algebra solver functions; Added unit tests for matrix index, dense matrix, and sparse matrix construction functions; Added unit tests for matrix types and utilities; Added unit tests for plain number modulus arithmetic; Added unit tests for probability functions; Added unit tests for relational comparison functions; Added unit tests for signal processing functions; Added unit tests for string formatting and printing functions; Added unit tests for the Chain type and factory function; Added unit tests for the Unit type and physical constants; Added unit tests for the expression parser subsystem; Added unit tests for the fraction function; Added unit tests for the solveODE function; Added unit tests for type conversion functions; Added unit tests for utility functions; Expanded unit test coverage for matrix functions; New browser test configuration infrastructure.
Dependencies
mathjs v15.2.0 release with updated dependencies and ESM support
This release updates the mathjs library to version 15.2.0, upgrading key dependencies including decimal.js to ^10.4.3, fraction.js to ^5.2.1, and typed-function to ^4.2.1. The package is now published as an ES module (type: module) with dual CommonJS/ESM entry points, and the minimum supported Node.js version has been raised to 18. A new code editor example is included, demonstrating integration with CodeMirror 6, KaTeX, and Vite.
(dependencies) · high confidence
Housekeeping
math.js v15.1.1 release
This update publishes version 15.1.1 of the math.js library. The release includes general maintenance and bug fixes across the codebase, continuing the evolution of the library's mathematical, matrix, and unit handling capabilities.
(repo-wide) · high confidence
Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
How this codebase got here
This is the PUBLIC form of this artifact. Findings are listed in full, but the details of SECURITY findings — which rule fired, in which file, on which line, and how to fix it — are deliberately withheld, and any secret-scanner results are excluded entirely. Where detail is absent here it was REMOVED FOR PUBLICATION; it is not missing from the analysis. The complete artifact is available from the repository owner.
Score
- CAI 56 → 56 (-0.6)
- Rubric changed (rubric-2026.09.11 → rubric-2026.09.18) — scores are not directly comparable.
Lenses
- Code Health 51 → 51 (+0.0)
- Architecture 92 → 82 (-9.9)
- Maturity 72 → 72 (+0.0)
- Readiness 66 → 49 (-16.3)
- Security 51 → 64 (+12.8)
- Performance 91 (new)
Resolved (10)
- Dependency hygiene PARTLY measured — npm pinning read, dependency currency not (no pnpm-resolved versions to grade)
- Documentation: no installation or build instructions (README.md)
- Documentation: no installation or build instructions (docs/datatypes/index.md)
- Documentation: no usage examples (docs/custom_bundling.md)
- Documentation: written for insiders (docs/expressions/security.md)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- Off-boarding risk: anonymized user #1
New (20)
- Critical CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- Low cohesion: Node (LCOM4 5) (src/expression/node/Node.js)
- Medium: security finding (details withheld)
- Medium: security finding (details withheld)
- Medium: security finding (details withheld)
- Off-boarding risk: anonymized user #1
- Outdated (npm): @babel/runtime
- Outdated (npm): @codemirror/language
- Outdated (npm): @codemirror/state
- Outdated (npm): complex.js
- Outdated (npm): decimal.js
- Outdated (npm): fraction.js
- Outdated (npm): github-markdown-css
- Outdated (npm): katex
- Outdated (npm): mathjs
- Outdated (npm): typed-function
- Projects may be oversized for their cohesion
Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
Survey your own repository
josdejong/mathjs was measured the same way every project in this corpus was: the same rubric, at a pinned commit, with the result published in full. Point a surveyor at a repository you know and see whether you agree with it.
About this page
- The score is its most recent published measurement, taken on 1 October 2026 at a pinned commit. It is not a live figure and does not change until the project is measured again.
- Measured at commit 8d214e050a0acb9f132405d55a96b683fa7b6324 — the exact code this score is about.
- Scored under rubric-2026.09.18 — the same rubric and the same method as every other entry in this index.
- Measured by watchdog.canine.dev using codehealth-analyzer preprod-e569280dd5e2.