Skip to content

Function Support

Basic Syntax

functionName(arg1, arg2, ...)

Built-in Functions

See Built-in Math Functions for the full list.

javascript
import { calc } from "a-calc";

calc("sqrt(16)"); // '4'
calc("abs(-5)"); // '5'
calc("pow(2, 3)"); // '8'
calc("max(1, 5, 3)"); // '5'
calc("sin(90)"); // '1'

Custom Functions

Pass functions via the second argument:

javascript
const double = (x) => x * 2;
calc("double(5)", { double }); // '10'
calc("double(x)", { double, x: 7 }); // '14'

const add = (a, b) => a + b;
calc("add(3, 4)", { add }); // '7'

Function Arguments

Arguments can be any valid expression:

javascript
calc("sqrt(9 + 16)"); // '5'
calc("max(1 + 2, 5 - 1)"); // '4'
calc("abs(x - y)", { x: 3, y: 10 }); // '7'

Nested Functions

javascript
calc("sqrt(pow(3, 2) + pow(4, 2))"); // '5' (Pythagorean theorem)
calc("abs(min(-5, max(1, 2)))"); // '5'
calc("round(sqrt(x))", { x: 10 }); // '3'

Lookup Priority

When a custom function has the same name as a built-in:

  1. Custom function (highest priority)
  2. Built-in function
javascript
// Built-in abs
calc("abs(-5)"); // '5'

// Custom overrides built-in
const abs = (x) => x * x;
calc("abs(-5)", { abs }); // '25'

Advanced Usage

Recursive Functions

javascript
const factorial = (n) => (n <= 1 ? 1 : n * factorial(n - 1));
calc("factorial(5)", { factorial }); // '120'

Function Factory

javascript
const createMultiplier = (factor) => (x) => x * factor;
const double = createMultiplier(2);
const triple = createMultiplier(3);

calc("double(5) + triple(3)", { double, triple }); // '19'

Released under the MIT License