Spanish Total.js
English
Documentation For AI agents
Contents

Macros

Compile a small rule language into a function with NEWMACRO(), for rules that users write.

.md GitHub

NEWMACRO(str, [nocompile], [isasync]) compiles a small rule language into a function. It is useful when users write rules in your application (prices, discounts, validations) and you do not want to run their JavaScript.

var macro = NEWMACRO([
    '// discount rule',
    'IF total > 1000 AND vip',
    '    RETURN discount(total, 15)',
    'ELSE IF total > 500',
    '    RETURN discount(total, 5)',
    'FI',
    'RETURN total'
].join('\n'));

var helpers = {};
helpers.discount = function(value, percentage) {
    return value - (value / 100 * percentage);
};

macro({ total: 1200, vip: true }, helpers); // 1020

The language has IF, ELSE IF, ELSE, FI, RETURN, AND, OR, the values TRUE, FALSE, YES, NO, OK and NULL, quoted values, comments with // and private variables with #:

var macro = NEWMACRO('#price = price * count\nIF #price > 100\nRETURN "big"\nFI\nRETURN "small"');

Names are converted to lower case, so properties of the model and names of helpers must be lower case. Avoid property names that contain the words if or else, because the compiler replaces them as keywords. With isasync the helpers can be async functions and the macro returns a Promise. With nocompile you get the generated JavaScript, which helps when you debug a rule.

Made in Europe