@bignum/template
Write formulas with template literals.
🚀 Features
- You can write formulas with template literals.
(f`0.3 - 0.1`
is easier to read than a statement like new Big(0.3).minus(0.1)
.) - Returns exact calculation results using arbitrary-precision arithmetic with BigInt.
(Similar to big.js.) - The calculation engine is customizable.
💿 Installation
npm install @bignum/template
📖 Usage
import { setupEngine } from "@bignum/template";
const f = setupEngine();
const num = 0.1;
const result = f`${num} + 0.1 * 2`;
console.log(result);
console.log(f`${0.2} + ${0.1}`);
console.log(0.2 + 0.1);
🧮 API
setupEngine([context]): BTEngine
Returns the calculation engine.
context
: An object for customizing calculations.
By default, calculations are performed using BigNum.
setupEngine context
TBA
BTEngine
Perform calculations using template literals.
Example:
import { setupEngine } from "@bignum/template";
const f = setupEngine();
console.log(f`${0.1} + 0.2`);
The calculation result usually returns a number
, but if the number
loses precision when converted to a string
, it returns a string
with the original precision is returned.
📝 Supported Syntax
Operators
The following operators are supported:
f`0.1 + 0.2`;
f`0.3 - 0.1`;
f`0.1 * 10`;
f`0.6 / 0.2`;
f`0.6 % 0.2`;
f`2 ** 3`;
f`4 ** (1/2)`;
f`8 ** (1/3)`;
f`(0.1 + 0.2) * 10`;
f`0.1 + 0.2 * 10`;
f`${0.3} + -${0.1}`;
f`41 == 41`;
f`41 == 1`;
f`41 != 41`;
f`41 != 1`;
f`1 <= 2`;
f`1 <= 1`;
f`1 <= 0`;
f`1 < 2`;
f`1 < 1`;
f`1 < 1`;
f`2 >= 1`;
f`1 >= 1`;
f`0 >= 1`;
f`2 > 1`;
f`1 > 1`;
f`0 > 1`;
Operand
Either write the numerical value as is in the template, or the template literal substitution is considered as an operand.
f`0.3 + -${0.1}`;
Variables
Variables can be accessed using identifiers. The supported variables are:
f`E`;
f`LN10`;
f`LN2`;
f`LOG2E`;
f`LOG10E`;
f`PI`;
f`SQRT1_2`;
f`SQRT2`;
Functions
You can call built-in functions by writing a Call expression.
f`trunc(12.34)`;
f`round(12.34)`;
f`floor(12.34)`;
f`ceil(12.34)`;
f`abs(-1)`;
f`sqrt(2)`;
🛸 Prior Art
- bigjs-literal
This package is similar to bigjs-literal in that it uses template literals for calculations, but bigjs-literal has a 49kB file for the parser alone.
The JavaScript file for the compiler that @bignum/template
has is 8kB (without minify). (However, there is no ability to compile it in advance.)