API
Every entry point, function and option. Every example runs live — edit the input and see.
mz is the library (mathzetta/all, or window.MathZetta from the script tag); input is the text box.
These same examples run in npm test, so what you read here is what the code does.
'mathzetta' — the core
import { parse, parseTree, parseSteps, fromPostfix, toPostfix } from 'mathzetta';The parser, the operator table and the tree tools. No output formats: add the entries you need, or take everything with mathzetta/all.
parse(text, options?) → string[] (also exported as parseToPostfix)
Standard postfix for maths written almost any way — plain text, LaTeX, unicode, JavaScript, Python. Throws on bad input. parseToPostfix is the same function under its older name.
| option | type | |
|---|---|---|
names | string[] | Multi-letter names to keep whole; otherwise runs of letters may be read as products. |
values | string[] | Names that are never functions: `k (x + 1)` is a product, where `f (x + 1)` is a call. |
blocks | (text, scope) => string | null | How `{{…}}` is filled for this call. Default: the handler set with setBlockHandler() — calculateBlock once mathzetta/calculate is loaded. `null` leaves blocks as plain groups. |
scope | object | Variable values passed to `blocks`. |
keepIntermediateSteps | boolean | Return every stage (see parseSteps) instead of postfix. |
allowUnvalidated | boolean | On a malformed expression return the raw postfix instead of throwing. |
return mz.parse(input);return mz.parse(input);return mz.parse(input);return mz.parse(input);return { without: mz.parse(input), withNames: mz.parse(input, { names: ['cost', 'rate'] }) };return { asCall: mz.parse('f (x + 1)'), asValue: mz.parse(input, { values: ['k'] }) };return mz.parse(input);return mz.parse(input, { blocks: null });return mz.parse(input, { blocks: (text, scope) => mz.calculate(text, scope, { decimal: true, places: 4 }).text });return mz.parse(input, { scope: { a: 1, b: 3 } });return mz.parse(input, { keepIntermediateSteps: true });try { return { strict: mz.parse(input) }; } catch (e) { return { strict: e.message, allowUnvalidated: mz.parse(input, { allowUnvalidated: true }) }; }parseTree(text, options?) → Node
The expression as a tree. Every node has an `id`: the index of its token in the postfix, which every outputter uses to point at parts.
return mz.parseTree(input);parseSteps(text, options?) → { original, mode, cleaned, cleanSteps, tokens, rawPostfix, tree, postfix, error }
Every stage, for debugging an input. Never throws — a failure has an `error` and whatever stages completed.
const s = mz.parseSteps(input); return { mode: s.mode, cleaned: s.cleaned, tokens: s.tokens, rawPostfix: s.rawPostfix, postfix: s.postfix };return mz.parseSteps(input).error;clean(text, options?) → { cleaned, stringMap, steps }
The cleaner on its own: what the tokenizer will see after spellings are unified.
return mz.clean(input).cleaned;fromPostfix(tokens) → Node · toPostfix(tree) → string[] · validatePostfix(tokens) → boolean
Tree ⇄ postfix. Variadic operators carry their operand count (`a b c 3 max`).
return mz.toPostfix(mz.fromPostfix(input.split(' ')));return [mz.validatePostfix(input.split(' ')), mz.validatePostfix(['x', '1', '+'])];treeOf(input, options?) · asTree(input) · walk(tree, visit) · firstVariable(tree) · num · sym · op · leaf
treeOf accepts text, postfix or a tree and gives the tree (what every outputter does first). walk visits parents before children.
const seen = []; mz.walk(mz.treeOf(input), (n) => seen.push(n.id + ':' + (n.op ?? n.value))); return seen;return mz.firstVariable(mz.treeOf(input));return mz.toPostfix(mz.op('+', [mz.sym(input), mz.num(1)]));operator(token) · operatorNames() · isOperator · precedenceOf · getOperatorPrecedence · needsParens(parentOp, childOp, side) · isCustomFunction · isNumeric(text) · VARIADIC · CUSTOM_PREFIX · getSupportedOperations()
The operator table: precedence, associativity, arity and fixity of every token that can appear in postfix. getOperatorPrecedence is precedenceOf under its older name. isNumeric says whether a postfix token is a number.
return mz.operator(input);return mz.operatorNames().length + " operators, e.g. " + mz.operatorNames().slice(0, 12).join(" ");return { timesOverPlus: mz.needsParens('*', '+', 'left'), plusOverTimes: mz.needsParens('+', '*', 'left'), custom: mz.isCustomFunction('\\:f') };return mz.getSupportedOperations().calculus;return { precedence: mz.precedenceOf(input), timesIsLower: mz.precedenceOf('*') < mz.precedenceOf(input), numbers: ['3.5', '-2', 'x', '1e3'].map((t) => t + ': ' + mz.isNumeric(t)) };setBlockHandler(handler | null)
Set the default for `{{…}}` blocks in every later parse. mathzetta/calculate calls this with calculateBlock when it loads.
mz.setBlockHandler((text) => '0'); const out = mz.parse(input); mz.setBlockHandler(mz.calculateBlock); return out;GREEK · bracketOp · needsBrackets · unaryNeedsBrackets · isImplicitProduct · bracketedSides · isMinusOneTimes · startsWithSign · isVariable · firstLeaf · smallWhole · customName · derivativeOrder
How a tree reads when written out — the decisions every outputter shares (and Inline Math uses): when brackets are needed, when `2x` has no dot.
const t = mz.treeOf(input); return { left: mz.needsBrackets(t, t.args[0], 'left'), right: mz.needsBrackets(t, t.args[1], 'right') };return { '2·x': mz.isImplicitProduct(mz.treeOf('2'), mz.treeOf('x')), 'x·2': mz.isImplicitProduct(mz.treeOf('x'), mz.treeOf('2')), alpha: mz.GREEK.alpha };MATRICES · matrixRows(node)
Matrices: `pmatrix`, `bmatrix` and `vmatrix` (the determinant) take one operand per row. `matrixRows` gives the rows of entries for those, and for a list of equally long lists written as one, `[[1, 2], [3, 4]]`.
return { postfix: mz.parse(input).join(' '), rows: mz.matrixRows(mz.treeOf(input)).map((r) => r.map((n) => n.value)), brackets: mz.MATRICES.pmatrix };'mathzetta/plain' — the core, without reading code
import { parse, parseTree, treeOf, … } from 'mathzetta/plain'; // or <script src="…/mathzetta@1/build/mathzetta.plain.min.js">The same exports as the core, without the reader for code spellings (numpy, SymPy, SQL, spreadsheet formulas, GLSL): about 5 KB gzipped smaller, for pages that read maths and LaTeX only. Plain text, LaTeX, unicode and JavaScript-style maths read the same. The code outputs (mathzetta/python, /sql, /excel, /glsl) keep the full reader, since reading back what they write belongs with them. The script-tag files are mathzetta.plain.min.js and the plain-* flavours on the CDN page.
what the full reader adds
Code spellings: in the full core np.sqrt(x) is √x and =SUM(A1:A3) a spreadsheet formula; mathzetta/plain reads np as the letters n and p, and refuses the formula. The examples here run the full library.
return mz.parse(input).join(' ');return mz.parse(input).join(' ');'mathzetta/latex'
import { toLaTeX } from 'mathzetta/latex';LaTeX, for KaTeX, MathJax or a paper.
toLaTeX(input, { wrap }?) → string
Accepts text, postfix or a tree.
| option | type | |
|---|---|---|
wrap | (node, latex) => string | Called for every subexpression with its LaTeX; return what to put in its place — e.g. a \class or \htmlClass wrapper carrying the node id. |
return mz.toLaTeX(input);return mz.toLaTeX(input);return mz.toLaTeX(input.split(' '));return mz.toLaTeX(input, { wrap: (node, tex) => (node.id === undefined ? tex : '{\\class{n' + node.id + '}{' + tex + '}}') });'mathzetta/mathml'
import { toMathML } from 'mathzetta/mathml';MathML, which browsers render natively. Each node's element has id="mz-<index>".
toMathML(input, { ids }?) → string
| option | type | |
|---|---|---|
ids | boolean | false leaves out the id="mz-<index>" each element carries for highlighting — MathML to paste elsewhere. |
return mz.toMathML(input);return mz.toMathML(input, { ids: false });'mathzetta/text'
import { toText } from 'mathzetta/text';Readable plain text.
toText(input) → string
return mz.toText(input);'mathzetta/speech'
import { toSpeech, toSpeechSegments, toAudioSpeech, toAudioSpeechSegments, SPEECH_WORDS, SPEECH_NAMES } from 'mathzetta/speech';The expression read aloud as a teacher would: toSpeech beside the drawing (a video, captions), toAudioSpeech for a listener who cannot see it (a screen reader). Every word can be changed; the segmented forms tag each piece with the node it describes, for captions that follow the maths.
toSpeech(input, { words, names, say }?) → string
| option | type | |
|---|---|---|
words | object | Connecting words to change; the keys are those of SPEECH_WORDS. |
names | object | What functions are called, e.g. { ln: "log" }; the defaults are SPEECH_NAMES. |
say | object | Whole phrases: operator or node type → (spokenOperands, node, speak) => phrase. |
return mz.toSpeech(input);return mz.toSpeech(input);return mz.toSpeech(input, { words: { eToThe: 'exp of' } });return mz.toSpeech(input, { names: { ln: 'log' } });return mz.toSpeech(input, { say: { '^': (parts) => parts[0] + ' raised to the power ' + parts[1] } });return Object.keys(mz.SPEECH_WORDS).slice(0, 16).join(", ") + " …";toAudioSpeech(input, { words, names, say }?) → string
For a listener who cannot see the maths: a compound radicand, exponent, subscript, denominator, argument … opens with "the quantity" and closes with an end word, dropped at the end. Same options as toSpeech.
return mz.toAudioSpeech(input) + " | video: " + mz.toSpeech(input);return mz.toAudioSpeech(input);return mz.toAudioSpeech(input, { words: { endAbsoluteValue: 'close bars' } });toSpeechSegments(input, options?) → [{ text, id }] · toAudioSpeechSegments(input, options?) → [{ text, id }]
The same phrases in pieces; `id` is the node each piece belongs to (Inline Math draws the same ids), so captions or a highlight can follow the words. toAudioSpeechSegments splits toAudioSpeech the same way, its "the quantity" and end words tagged with the group they open and close.
return mz.toSpeechSegments(input);return mz.toAudioSpeechSegments(input).map((s) => s.text + ' [' + s.id + ']').join(' ');SPEECH_WORDS · SPEECH_NAMES
The defaults the speech options change: SPEECH_WORDS the connecting words (the keys of `words`), SPEECH_NAMES what each function is called aloud (the keys of `names`).
return { [input]: mz.SPEECH_NAMES[input], names: Object.keys(mz.SPEECH_NAMES).length };return { [input]: mz.SPEECH_WORDS[input], words: Object.keys(mz.SPEECH_WORDS).length };'mathzetta/javascript'
import { toJavaScript } from 'mathzetta/javascript';Code using Math.*. For formulas over table rows see mathzetta/formulas.
toJavaScript(input) → string
return mz.toJavaScript(input);return mz.toJavaScript(input);'mathzetta/python'
import { toPython, toPythonFunction, fillPythonTemplate, readPythonTemplate, preparePythonTemplate, checkGeneratedPython, pythonName, UnsafeCodeError } from 'mathzetta/python';Python using math.* (or numpy, element-wise, or SymPy, symbolic and exact): an expression, a formula as a function, or a Python program with formula slots for users to customise. Generated code passes checkGeneratedPython, so a formula cannot call print, exec or open. Functions raise on 1/0, sqrt(-1) and overflow unless errors is 'nan'.
toPython(input, { numpy, sympy }?) → string
| option | type | |
|---|---|---|
numpy | boolean | Element-wise over arrays: np.where for ?:, np.logical_and for and, np.maximum for max, chained comparisons joined element-wise. |
sympy | boolean | Symbolic and exact: decimals and integer fractions as sympy.Rational, = as sympy.Eq, ?: as sympy.Piecewise, and derivatives, integrals, limits and sums as sympy.diff, integrate, limit and summation. Text throws. Not with numpy. |
return mz.toPython(input);return mz.toPython(input);return mz.toPython(input, { numpy: true });return mz.toPython(input, { numpy: true });return mz.toPython(input, { sympy: true });return mz.toPython(input, { sympy: true });toPythonFunction(input, { name, params, globals, functions, numpy, sympy, errors, columns, table }?) → { code, name, params, imports, formula, latex }
A def. `f(x, y) = …` names the function and its parameters; otherwise the parameters are the variables read, in order. Declared parameters are read whole (rate dt is rate·dt) and are all the formula may use, with `globals`; anything else throws, naming it. Derivatives and limits throw, unless sympy; an integral with limits uses scipy.
| option | type | |
|---|---|---|
name | string | The function's name: default the definition's, else 'f'. |
params | string[] | Its parameters, in order. |
globals | string[] | Other names it may read: module-level values of the program. |
functions | string[] | Functions it may call besides math.*. |
numpy | boolean | Element-wise over arrays: parameters become float arrays and 1/0 follows IEEE (inf, nan). Errors are judged on the result, so 1/x in a branch np.where did not take does not count. |
sympy | boolean | Symbolic and exact: derivatives, integrals, limits and sums work. The variables they bind become sympy.Symbol in the function; a parameter of the same name is substituted after, so f(x) = d/dx x³ gives f(2) = 12 and f(Symbol("x")) = 3x². errors 'nan' returns sympy.nan. Not with numpy or columns. |
columns | string[] | A table's header: the formula may use any column by name, matched as whole words in any case (2B is the column). They are read from the parameter `table` (default data): a row in plain Python, whole columns with numpy, where max(HR), sum(HR), mean(HR), median(HR) and stdev(HR) are over the column. |
table | string | The parameter holding the table (default data). |
errors | 'raise' | 'nan' | What 1/0, sqrt(-1) and overflow do. 'raise' (default): an exception (numpy: FloatingPointError when the result is not finite for finite inputs). 'nan': the function returns nan (numpy: inf and nan element by element). |
return mz.toPythonFunction(input).code;return mz.toPythonFunction(input);return mz.toPythonFunction(input, { name: 'growth', params: ['P', 'r', 'K'] }).code;try { mz.toPythonFunction(input, { name: 'growth', params: ['P', 'r', 'K'] }); } catch (e) { return e.message; }try { mz.toPythonFunction(input); } catch (e) { return e.message; }return mz.toPythonFunction(input, { errors: 'nan' }).code;return mz.toPythonFunction(input, { numpy: true }).code;return mz.toPythonFunction(input, { sympy: true }).code;return mz.toPythonFunction(input, { name: 'rate', params: ['data'], columns: ['player', 'AB', 'H', '2B'], numpy: true }).code;fillPythonTemplate(template, formulas?, { globals, functions, numpy, sympy, errors, columns, data }?) → string · readPythonTemplate(template) → { slots, data, numpy, sympy, errors }
A template is a Python program with slots: a line `# mathzetta: growth(P, r, K) = r P (1 - P/K)` gives the signature the program calls and a default formula. Filling replaces each slot with its def (and an import the program lacks), using formulas[name] or the default. Slots may call each other; each filled function gets .formula and .latex (for chart labels). A parameter written `data: columns` holds a table: pass its header as columns. `# mathzetta-data: file.csv` becomes DATA_FILE = "…" (options.data). `# mathzetta-options: numpy errors=nan` sets numpy and errors (or `sympy`); the options here override it. The command `mathzetta-python template.py slot=formula --run` fills (reading the CSV header) and runs; mathzetta/examples/python/logistic.py is a model; pyslots (a sibling project) turns templates into web pages, with matplotlib charts over baseball data.
const t = 'R, K = 0.4, 1000.0\n\n# mathzetta: growth(P, r, K, h) = r P (1 - P/K)\n\nprint(growth(50, R, K, 0))\n'; return mz.fillPythonTemplate(t, { growth: input });return mz.readPythonTemplate('# mathzetta: growth(P, r, K) = r P (1 - P/K)\n# mathzetta: harvest(P)\n');const t = '# mathzetta-data: batting.csv\n# mathzetta-options: numpy\n# mathzetta: keep(data: columns) = year >= 1990\n# mathzetta: y(data: columns) = HR\n'; return mz.fillPythonTemplate(t, { y: input }, { columns: ['player', 'year', 'AB', 'H', 'HR'], data: '/data/batting.csv' });preparePythonTemplate(template, formulas?, options?) → { program, error, description, data, slots }
What a form for a template needs, without throwing for a bad formula: each slot with its doc (the comment above it), default, formula, and either code, latex and tree (to draw it, e.g. with Inline Math) or error; program when every slot is right. Takes what fillPythonTemplate takes.
const t = '# How fast it grows.\n# mathzetta: growth(P, r, K) = r P (1 - P/K)\n# What is taken.\n# mathzetta: harvest(P) = 0.1 P\n'; const p = mz.preparePythonTemplate(t, { growth: input }); return { program: p.program, slots: p.slots.map((s) => ({ name: s.name, doc: s.doc, error: s.error, latex: s.latex })) };checkGeneratedPython(code, { variables, functions }?) → code
The whitelist the functions pass: numbers, "…" strings, operators, the listed names, math.* and the built-ins the generator writes. Names are compared NFKC-normalised, as Python reads them. Throws UnsafeCodeError.
return mz.checkGeneratedPython(input, { variables: ['x'] });try { mz.checkGeneratedPython(input, { variables: ['x'] }); } catch (e) { return e.message; }pythonName(name) → string · class UnsafeCodeError
pythonName is what a variable is called in the generated Python: a Python keyword gets a trailing underscore, so a program that fills its own variables (or a template's caller) uses the same spelling. UnsafeCodeError is what the checks throw (the same class as mathzetta/formulas').
return [input, 'x', 'class', 'rate'].map((n) => n + ' → ' + mz.pythonName(n)).join(', ');try { mz.checkGeneratedPython(input, { variables: ['x'] }); } catch (e) { return { unsafe: e instanceof mz.UnsafeCodeError, message: e.message }; }'mathzetta/excel'
import { toExcel, forXlsxFile } from 'mathzetta/excel';A spreadsheet formula for Excel and Google Sheets. Powers are bracketed (in a spreadsheet -x^2 is (-x)^2 and 2^3^2 is 64), ATAN2 takes (x, y) and LOG (number, base), logic is AND/OR/NOT, choices IF. No infinity, no symbolic maths: those throw. MathZetta reads these formulas back (a formula starting with = is read as a spreadsheet's: cells, ranges, its ^ and minus).
toExcel(input, { cells, ranges, equals }?) → string
| option | type | |
|---|---|---|
cells | object | (name) => ref | Variables as cell references: { Revenue: 'B2' }. |
ranges | object | (name) => range | A variable as a column, for one-argument sum, mean, max, min, median, stdev: { Profit: 'D2:D101' }. |
equals | boolean | Start with = (default true). |
return mz.toExcel(input);return mz.toExcel(input);return mz.toExcel(input, { cells: { Profit: 'D7' }, ranges: { Profit: 'D2:D101' } });return mz.parse(input).join(" ");forXlsxFile(formula) → string
A formula as it is stored inside an .xlsx file, for code that writes the file itself: no leading =, and the functions newer than Excel 2007 with the _xlfn. prefix Excel expects (without it they open as #NAME?). What you type into a cell is toExcel's output.
return mz.forXlsxFile(input);return mz.forXlsxFile(mz.toExcel(input));'mathzetta/sql'
import { toSQL } from 'mathzetta/sql';A SQL expression: PostgreSQL by default, or SQLite.
toSQL(input, { dialect, quoteIdentifiers, stringQuote, columns }?) → string
| option | type | |
|---|---|---|
dialect | 'postgres' | 'sqlite' | SQLite gets real division, MAX/MIN, 9e999 for ∞, and throws "No SQLite SQL for …" for what it cannot run (5!, gcd, calculus). |
quoteIdentifiers | boolean | Write variables as "double-quoted" identifiers. |
stringQuote | string | Quote for string literals; default: as typed (postgres), ' (sqlite). |
columns | string[] | Names that are always columns even if they look like constants (e, pi). |
return mz.toSQL(input);return mz.toSQL(input, { dialect: 'sqlite' });return mz.toSQL(input, { quoteIdentifiers: true });return mz.toSQL(input, { stringQuote: "'" });return { asConstant: mz.toSQL(input), asColumn: mz.toSQL(input, { columns: ['e'] }) };'mathzetta/glsl'
import { toGLSL, GLSL_HELPERS, filterShader, filterVertexShader, FILTER_NAMES, FILTER_VALUES, FILTER_FUNCTIONS, NEIGHBOURHOOD, GEOMETRY, PLACES, REACH, IMPLICIT_PICTURES, COLOUR_SPACES, COLOUR_FUNCTIONS, filterPictureCalls } from 'mathzetta/glsl';Shader code: an expression with floats throughout, or a whole fragment shader that applies expressions to an image's pixels. The shareable filter format and WebGL runner built on this are the qblur package.
toGLSL(input, { version }?) → string · GLSL_HELPERS
| option | type | |
|---|---|---|
version | 100 | 300 | GLSL ES 1.0 (WebGL 1, default) or 3.0 (WebGL 2). |
return mz.toGLSL(input);return mz.toGLSL(input, { version: 300 });return mz.GLSL_HELPERS.split('\n').slice(0, 5).join('\n') + '\n…';filterShader(spec, { version, names, values, uniforms, blend, images }?) → string · filterVertexShader({ version }?) → string
A complete fragment shader. `spec` is one expression for the colour, or { r, g, b, a, rgb, rgba }. Inside it: r g b a x y px py t, gray, unchanged, pixel(), blur(), if … then … else.
| option | type | |
|---|---|---|
version | 100 | 300 | as toGLSL |
names | string[] | extra function names |
values | string[] | extra value names (never calls) |
uniforms | object | name → GLSL type, declared as uniforms |
blend | boolean | blend the result with the input by an opacity uniform |
images | string[] | object | other pictures the expression samples |
return mz.filterShader(input).split('\n').slice(-8).join('\n');return mz.filterShader({ r: input, b: 'g' }, { values: ['k'], uniforms: { k: 'float' } }).split('\n').filter((l) => /uniform|mz_rgba/.test(l)).join('\n');return mz.FILTER_NAMES.join(', ');return mz.filterVertexShader().split('\n').slice(0, 4).join('\n') + '\n…';FILTER_NAMES · FILTER_VALUES · FILTER_FUNCTIONS · NEIGHBOURHOOD · GEOMETRY · PLACES · REACH · IMPLICIT_PICTURES
The vocabulary of a filter expression, for an editor that completes or checks names. FILTER_NAMES is all of it; FILTER_VALUES the names that are values (px, rgb, gray …) and FILTER_FUNCTIONS the calls (pixel, luma …); NEIGHBOURHOOD the calls that read nearby pixels (blur, gaussian …) and REACH how far they may reach, in pixels (square kernels and lines); GEOMETRY the calls that move the picture (zoom, rotate, crop …) and PLACES how another picture is fitted (cover, fit …); IMPLICIT_PICTURES the pictures every filter has without declaring them.
return { values: mz.FILTER_VALUES, neighbourhood: mz.NEIGHBOURHOOD, reach: mz.REACH, geometry: mz.GEOMETRY, places: mz.PLACES, implicit: mz.IMPLICIT_PICTURES };return mz.FILTER_NAMES.includes(input);COLOUR_SPACES · COLOUR_FUNCTIONS
The colour spaces a filter can work in, and the to<space>(c) / from<space>(c) calls that convert to and from them.
return { spaces: mz.COLOUR_SPACES, functions: mz.COLOUR_FUNCTIONS.slice(0, 6).join(', ') + ' …' };filterPictureCalls(tree, pictures) → tree
A filter expression's tree with every read of a picture made explicit — luma(mask) becomes a sample of mask at this pixel, zoom(2) a sample at the moved position. `pictures` is the set of extra picture names. Both of qblur's runners (GPU and CPU) start from it.
return mz.toPostfix(mz.filterPictureCalls(mz.treeOf(input), new Set(['mask']))).join(' ');return mz.toPostfix(mz.filterPictureCalls(mz.treeOf(input), new Set())).join(' ');'mathzetta/evaluate'
import { evaluate } from 'mathzetta/evaluate';A value in double precision, computed without generating code. Fast and simple; for exact answers use calculate.
evaluate(input, scope?) → number | boolean | string | array
return mz.evaluate(input, { x: 3 });return mz.evaluate(input);return mz.evaluate(input);'mathzetta/calculate'
import { calculate, calculateBlock, MathError, UnknownError } from 'mathzetta/calculate';Exact where possible — fractions, whole numbers of any size, surds, π and e, trig at the standard angles, exact logs — and numeric derivatives, definite integrals, limits and infinite sums otherwise, reported exactly when the answer is recognisable. Loading this entry switches on {{…}} blocks in every input.
calculate(input, scope?, { decimal, places, digits, maxDigits }?) → { value, text, exact }
`value` is plain JS (number, boolean, string, array); `text` is MathZetta-readable ('1/2', '2*sqrt(2)'); `exact` is false when part of it is a rounded double. Throws MathError when there is no answer (1/0, √−1, a divergent integral) and UnknownError when it can't be worked out (an unset variable, an integral without limits).
| option | type | |
|---|---|---|
decimal | boolean | Write the answer as a decimal. |
places | number | Round the written answer to this many decimal places. |
digits | number | Significant digits for answers that aren't exact (12). |
maxDigits | number | Longest whole number written out in full (50); beyond it, d.ddd*10^(k). |
return mz.calculate(input);return mz.calculate(input).text;return mz.calculate(input).text;return mz.calculate(input).text;return mz.calculate(input).text;return mz.calculate(input).text;return mz.calculate(input).text;return mz.calculate(input, { x: 2 }).text;return mz.calculate(input, {}, { decimal: true }).text;return mz.calculate(input, {}, { places: 3 }).text;return mz.calculate(input, {}, { digits: 4 }).text;return mz.calculate(input, {}, { maxDigits: 10 }).text;try { return mz.calculate(input); } catch (e) { return e.constructor.name + ': ' + e.message; }try { return mz.calculate(input); } catch (e) { return e.constructor.name + ': ' + e.message; }calculateBlock(text, scope?) → string
What replaces a `{{…}}` block: a leading ~ asks for a decimal, ~3 for three places; "undefined" when there is no answer; the text itself when it can't be worked out.
return mz.calculateBlock(input);return mz.calculateBlock(input);class MathError · class UnknownError
What calculate throws: MathError when there is no answer (1/0, √−1, a divergent integral), UnknownError when there may be one but it can't be worked out (an unset variable). Test with instanceof to tell "undefined" from "not known".
try { return mz.calculate(input).text; } catch (e) { return { noAnswer: e instanceof mz.MathError, notKnown: e instanceof mz.UnknownError, message: e.message }; }'mathzetta/formulas'
import { strToFunction, strToSQL, strToExcel, createRowEvaluator, checkGeneratedJs, isSafeGeneratedJs, UnsafeCodeError } from 'mathzetta/formulas';Formulas over the columns of a table: names are matched as whole words, case-insensitively, and become c0, c1, … in JavaScript or "quoted" identifiers in SQL. This is what tabview, tabc and sqldn use.
strToFunction(header, formula) → { success, jsFunction, postfixArray, unknownStrings, … }
return mz.strToFunction(['Price', 'Qty'], input).jsFunction;return mz.strToFunction(['Price', 'Qty'], input).unknownStrings;createRowEvaluator(jsFunction) → (row) => value
Compiles the generated code (and only that) into a function of a row array.
return mz.createRowEvaluator(mz.strToFunction(['Price', 'Qty'], input).jsFunction)([2.5, 4]);checkGeneratedJs(code, { variables }?) → code · isSafeGeneratedJs(code, options?) → boolean · class UnsafeCodeError
The whitelist in front of new Function. Formulas come from users, so generated code is compiled only if it is made of numbers, "…" strings, operators and allowed names — the variables you list, plus the Math/Number/Array members the generator writes. Unknown names (alert, fetch), computed members (x["constructor"]), template literals and other quotes are refused with UnsafeCodeError. createRowEvaluator calls it; call it yourself before compiling generated code any other way.
return mz.checkGeneratedJs(mz.strToFunction(['Price', 'Qty'], input).jsFunction, { variables: /^c\d+$/ });const r = mz.strToFunction(['Price'], input); let refused; try { mz.checkGeneratedJs(r.jsFunction, { variables: /^c\d+$/ }); } catch (e) { refused = e.message; } return { unknown: r.unknownStrings, refused, evaluator: mz.createRowEvaluator(r.jsFunction)([1]) };return mz.strToFunction(['name'], input).jsFunction;return [mz.isSafeGeneratedJs(input, { variables: ['r', 'g', 'b'] }), mz.isSafeGeneratedJs('c0["constructor"]', { variables: /^c\d+$/ })];strToExcel(header, formula, selections?, { ranges }?) → { success, excelFormula(cellOf), … }
A spreadsheet formula over columns, parsed once: excelFormula(cellOf) writes it with each column as cellOf(index), so it can be written for every row (tabview's .xlsx export does).
return mz.strToExcel(['Name', 'Revenue', 'Cost'], input).excelFormula((i) => 'ABC'[i] + 7);strToSQL(header, formula, selections?, { dialect }?) → { success, sqlExpression, … }
return mz.strToSQL(['H', 'AB'], input, new Map(), { dialect: 'sqlite' }).sqlExpression;'mathzetta/all'
import * as mz from 'mathzetta/all'; // or <script src="build/mathzetta.min.js"> → window.MathZettaEverything above, plus every format at once.
toUnified(input) → { latex, mathml, speech, javascript, python, sql, glsl, exp, op, postfix }
return mz.toUnified(input);convert(input, format) → string
format: javascript | js | python | py | latex | tex | mathml | mml | speech | glsl | sql | excel | sheets | text
return mz.convert(input, 'python');getMathMLIdMap() · resetIdTracking()
After toUnified(): MathML element id (mz-3) → every format of that subexpression, for pages that show details on hover.
mz.toUnified(input); return [...mz.getMathMLIdMap().keys()];MathZetta (object) · default export mathZetta(text, format)
Module users get the MathZetta object and a default export (parse + convert in one call). From the script tag, window.MathZetta is that object itself.
const lib = mz.MathZetta ?? mz; // the object, whichever way the library was loaded
return { exports: Object.keys(lib).length, viaDefault: (mz.default ?? ((t, f) => lib.convert(t, f)))(input, 'latex') };