decimal.js-formulas
v0.1.0
Published
Formula parser for decimal.js
Readme
decimal.js-formulas
Lightweight formula parser and evaluator for Decimal.js. It tokenizes input, builds an AST, and either compiles to an evaluator function or assembles a function from generated code. Internals are exposed for advanced use.
Install
bun add decimal.js-formulas decimal.jspnpm add decimal.js-formulas decimal.jsnpm i decimal.js-formulas decimal.jsUsage
Compiled evaluator (recommended):
import { createFormula } from "decimal.js-formulas/compiled";
const evalFn = createFormula("max(1, x) + 2 * 3");
evalFn({ x: 4 }); // Decimal(11)Assembled evaluator (generated JS body, faster):
import { createFormula } from "decimal.js-formulas/assembled";
const evalFn = createFormula("(x + 2).pow(3) / 2");
evalFn({ x: 2 }); // Decimal(8)You can type formula variables by passing a generic type to createFormula:
import { createFormula } from "decimal.js-formulas/compiled";
const myFormula = createFormula<{ x: number, y: number }>("x + 2 * y");
myFormula({ x: 1, y: 2 }); // Decimal(5)
myFormula({ x: 1 }); // Error: Missing required variable "y"Internals
All internals are available by importing from decimal.js-formulas/internals. This includes:
tokenizeFormulaparseFormulacompileFormulaassembleFormula- types and utility helpers
Testing
This project uses Bun’s test runner.
bun testNotes
- Peer dependency
decimal.jsis required at runtime.
