micro-math-kernel
v0.1.0
Published
Zero-dependency math operations micro-kernel with a pluggable architecture.
Maintainers
Readme
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.tsfiles. - 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-kernelQuick 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 operationsCompose 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.5Documentation
- Getting Started – installation checklist and first kernel.
- Usage Guide – lifecycle patterns and plugin management.
- API Reference – method signatures and bundled plugins.
- Examples – runnable scripts and plugin recipes.
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. Useoptions.overrideto replace an existing operation, andoptions.pluginNamewhen registering on behalf of a plugin.removeOperation(name, options?)– remove an operation. A plugin can only remove its own operations unlessoptions.forceis 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 thenew MathKernel()constructor.createDefaultKernel()– instantiate a kernel preloaded with the curateddefaultPluginstuple.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 duringunloadPlugin.
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 automaticallyThe 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 todist/.npm run build:test– compile the test-only project underdist-tests/.npm test/npm run test:coverage– build everything and run the Node test suite withc8, enforcing 100% coverage and emittingcoverage/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.
- Clone the repository:
git clone https://github.com/ersinkoc/micro-math-kernel.gitand install dependencies withnpm install. - Make your changes, keeping linting and formatting consistent.
- Run the full suite with
npm testto ensure everything passes (coverage is enforced). - 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.
- Ensure the code builds and tests succeed:
npm run buildandnpm test. - Update
package.jsonversion according to semantic versioning. - Run
npm packto inspect the tarball contents. - When ready, publish with
npm publish(usenpm publish --access publicfor the first release). - Tag the release in source control and update the changelog if applicable.
License
MIT © Ersin Koç
