Macros
NEWMACRO() and the function it returns.
On this page
API
method
NEWMACRO(str, [nocompile], [isasync])
Compiles a simple macro script into a JavaScript function.
NEWMACRO(str, [nocompile], [isasync])| Parameter | Type | Description |
|---|---|---|
str |
String |
The macro source. |
nocompile? |
Boolean |
Returns the generated JavaScript code as a string. Default: false |
isasync? |
Boolean |
Creates an async function. Default: false |
Returns Function|String A Function(model, helpers), or the code with nocompile.
Macros let users write small rules without JavaScript. Supported: IF, ELSE IF, ELSE, FI, RETURN, AND, OR, TRUE/FALSE/YES/NO/OK, NULL, quoted values, helper calls NAME(args), private variables #name and comments //. Keywords are case-insensitive. Model properties and helper names are converted to lower case, so keys in the model and helpers must be lower case. Avoid property names that contain if or else (for example verified), because the compiler replaces those letters as keywords. More statements can be on one line separated by ;.
The compiled function has the signature fn(model, helpers); helpers run with the model as this. With isasync every helper call is awaited and the function returns a Promise.
var fn = NEWMACRO('IF price > 100\n\tRETURN "expensive"\nFI\nRETURN discount(price)');
fn({ price: 200 }, {}); // expensive
fn({ price: 50 }, { discount: function(price) { return price * 0.9; } }); // 45
var fn = NEWMACRO('#total = price * count\nRETURN rate(#total)', false, true);
var value = await fn({ price: 2, count: 3 }, { rate: async function(val) { return val * 1.2; } });
delegate
fn(model, [helpers])
The function returned by NEWMACRO().
fn(model, [helpers])| Parameter | Type | Description |
|---|---|---|
model |
Object |
The data. |
helpers? |
Object |
Functions used by the macro. |
Returns Object|Promise The value of RETURN.
model gives the values of properties; helpers is an object of functions called by name from the macro. Private #variables live only during one call.
var check = NEWMACRO('IF age >= 18 AND active\nRETURN TRUE\nFI\nRETURN FALSE');
check({ age: 20, active: true }); // true