Connecting numerical functions
nerdamer.connect lets Nerdamer use numerical functions from another library or from your own code. Expressions stay exact; the connected function runs only when there are numbers to compute.
Pass the names to connect and an object that has them. Nerdamer doesn't load the library for you: pass one you've already imported.
With Math.js
import nerdamer from 'nerdamer';
import * as math from 'mathjs';
nerdamer.connect(['zeta', 'combinations'], math);
nerdamer('zeta(x)').text();
// zeta(x)
nerdamer('zeta(x)').evaluate({ x: 2 }).text();
// about 1.644934066848 (π²/6)
const f = nerdamer('zeta(x)+1').buildFunction(['x']);
f(2);
// about 2.644934066848
nerdamer('combinations(5,2)').evaluate().text();
// 10
The call is synchronous. If your runtime needs import() to load Math.js, that's about loading the module, not about connect.
With your own functions
nerdamer.connect(['double'], { double: (x: number) => 2 * x });
nerdamer('double(x)').text(); // double(x)
nerdamer('double(x)').evaluate({ x: 2 }).text(); // 4
To connect every function an object has, pass '*':
nerdamer.connect(['*'], {
f1: (x: number) => 2 * x,
f2: (x: number) => 3 * x,
label: 'ignored' // not a function: skipped
});
This also connects helper functions the object happens to have, which may mean nothing in an expression. List the names when that matters.
When the connected function runs
- While parsing: never. A connected name stays as written, as in
zeta(x). - In
evaluate(): once all its arguments are numbers. - In
buildFunction(): always, as part of the compiled function.
For a function Nerdamer already knows, such as cos, Nerdamer keeps its own exact rules and uses the connected function only for numbers.
Values
A connected function receives JavaScript numbers and must return a number or a boolean. Other values, such as Math.js matrices, complex numbers or big numbers, aren't converted.
Without the nerdamer object
The same thing is available as connectFunctions from nerdamer/core:
import * as math from 'mathjs';
import { connectFunctions } from 'nerdamer/core';
connectFunctions(['zeta'], math);
