Skip to content

ersinkoc/micro-math-kernel

Repository files navigation

micro-math-kernel

micro-math-kernel is a zero-dependency math micro-kernel for TypeScript and modern Node.js runtimes. It exposes a tiny MathKernel core that loads modular plugins so you can tailor the available operations—from elementary arithmetic to complex analysis and matrix decompositions—without pulling in heavyweight dependencies.

Highlights

  • Pluggable architecture with strict plugin isolation and predictable teardown.
  • Zero runtime dependencies with an ESM build and bundled .d.ts files.
  • Deterministic numeric utilities with rich validation and descriptive errors.
  • Batteries-included plugin suite spanning arithmetic, calculus, statistics, complex numbers, linear algebra, and number theory.

Repository

Hosted at github.com/ersinkoc/micro-math-kernel.

Installation

npm install micro-math-kernel

Quick Start

import { createDefaultKernel } from "micro-math-kernel";

const kernel = createDefaultKernel();

kernel.execute("add", 13, 29);           // 42
kernel.execute("complexFFT", [1, 2, 3]); // FFT with zero-padding
kernel.execute("matrixSVD", [[3, 0], [0, 2], [0, 0]]);
kernel.listOperations();                 // enumerate registered operations

Compose Your Own Kernel

import {
  createKernel,
  basicArithmeticPlugin,
  statisticsPlugin,
  createPlugin
} from "micro-math-kernel";

const kernel = createKernel({
  plugins: [basicArithmeticPlugin, statisticsPlugin]
});

kernel.defineOperation(
  "weightedMean",
  (values: number[], weights: number[]) => {
    if (values.length !== weights.length || values.length === 0) {
      throw new RangeError("values and weights must be non-empty arrays of equal length.");
    }
    const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
    return values.reduce((sum, value, index) => sum + value * weights[index]!, 0) / totalWeight;
  }
);

kernel.execute("weightedMean", [1, 3, 5], [1, 1, 2]); // 3.5

Documentation

API Overview

MathKernel

  • new MathKernel({ plugins? }) – instantiate a kernel, optionally preloading plugin descriptors.
  • defineOperation(name, handler, options?) – register an operation and receive a teardown callback. Use options.override to replace an existing operation, and options.pluginName when registering on behalf of a plugin.
  • removeOperation(name, options?) – remove an operation. A plugin can only remove its own operations unless options.force is truthy.
  • hasOperation(name) / getOperation(name) – query registered operations without invoking them.
  • listOperations() – return a snapshot of { name, plugin } pairs for all registered operations.
  • execute(name, ...args) – call an operation, forwarding arguments verbatim.
  • loadPlugin(descriptor) / use(descriptor) – load a plugin, running its setup and capturing an optional teardown.
  • unloadPlugin(name) – remove a plugin and automatically clean up its registered operations.
  • listPlugins() – list the names of currently loaded plugins.

Factory Helpers

  • createKernel({ plugins? }) – convenience wrapper that mirrors the new MathKernel() constructor.
  • createDefaultKernel() – instantiate a kernel preloaded with the curated defaultPlugins tuple.
  • createPlugin(name, setup | operations) – create a plugin descriptor from an imperative setup function or a plain object mapping operation names to handlers. When a setup function returns a teardown it is invoked automatically during unloadPlugin.

Plugin Descriptors

Plugins are plain objects with name and setup fields. The setup receives a scoped API with defineOperation, removeOperation, hasOperation, getOperation, listOperations, and execute. Plugin names are normalized to trimmed strings, and duplicate loads are rejected.

Plugin Lifecycle Patterns

import { MathKernel, createPlugin } from "micro-math-kernel";

const scalerPlugin = createPlugin("vector-scale", (kernel) => {
  kernel.defineOperation("scaleVector", (vector: number[], factor: number) =>
    vector.map((value) => value * factor)
  );

  return () => {
    kernel.removeOperation("scaleVector", { pluginName: "vector-scale", force: true });
  };
});

const kernel = new MathKernel();
const teardown = kernel.use(scalerPlugin);

kernel.execute("scaleVector", [1, 2, 3], 10); // [10, 20, 30]
teardown?.();                                   // manual teardown (optional)
kernel.unloadPlugin("vector-scale");            // invokes teardown automatically

The kernel enforces plugin ownership: attempts to remove or override operations from another plugin throw unless force: true is supplied.

Built-in Plugins

Plugin Description Operations
basic-arithmetic Fundamental numeric helpers with guardrails for invalid input. add, subtract, multiply, divide, modulo, clamp
advanced-math Power functions and safe roots/factorials. power, sqrt, factorial, nthRoot
statistics Descriptive statistics over numeric arrays or argument lists. sum, mean, median, mode, variance, stddev, min, max, range, quantile, geometricMean
calculus Numeric differentiation, Simpson integration, and bisection root solving. differentiate, integrate, solveEquation
matrix Core linear-algebra routines using rectangular input validation. matrixAdd, matrixSubtract, matrixMultiply, matrixTranspose, matrixDeterminant, matrixIdentity, matrixInverse
matrix-decomposition Factorisation suite across symmetric and general matrices. matrixLU, matrixCholesky, matrixQR, matrixEigenSymmetric, matrixSVD
number-theory Discrete helpers for integers and combinatorics. gcd, lcm, isPrime, primeFactors, fibonacci, binomial
complex Rich complex arithmetic, transcendental functions, polar conversions, and FFT/IFFT transforms. complexAdd, complexSubtract, complexMultiply, complexDivide, complexConjugate, complexMagnitude, complexPhase, complexNormalize, complexExp, complexLog, complexSin, complexCos, complexTan, complexSinh, complexCosh, complexTanh, complexPow, complexFromPolar, complexToPolar, complexToString, complexFFT, complexIFFT

Scripts and Testing

  • npm run build – compile the TypeScript sources to dist/.
  • npm run build:test – compile the test-only project under dist-tests/.
  • npm test / npm run test:coverage – build everything and run the Node test suite with c8, enforcing 100% coverage and emitting coverage/ artifacts.

Contributing

Contributions are welcome! Please fork the repository, create a feature branch, and open a pull request with clear motivation and tests. For larger changes, open an issue first to discuss what you would like to change.

  1. Clone the repository: git clone https://github.com/ersinkoc/micro-math-kernel.git and install dependencies with npm install.
  2. Make your changes, keeping linting and formatting consistent.
  3. Run the full suite with npm test to ensure everything passes (coverage is enforced).
  4. Submit a pull request describing the change and any additional context.

Reporting Security Issues

If you discover a security vulnerability, please do not open a public issue. Contact the maintainers directly so we can coordinate a fix and release.

Releasing / Publishing

This package is prepared for publication on the npm registry.

  1. Ensure the code builds and tests succeed: npm run build and npm test.
  2. Update package.json version according to semantic versioning.
  3. Run npm pack to inspect the tarball contents.
  4. When ready, publish with npm publish (use npm publish --access public for the first release).
  5. Tag the release in source control and update the changelog if applicable.

License

MIT © Ersin Koç

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published