Astraia

Astraia is a library which simplify JSON objects.
Astraia simplifies an object by specified rules.
Astraia can optimize abstract syntax tree (AST) represented by JSON object.

Install

Installing Astraia:

npm install astraia

Using module (node.js):

var A = require('astraia');

Using module (browser):

<script src='astraia.js'></script>

Using Astraia

Astraia simplifies an object by specified rules.
This is an example that simplifies AST which consists of addition and subtraction.


var rules = [{
  pattern: {
    "type": A.eqv("add"),
    "left": A.number,
    "right": A.number
  },
  action: function(obj) {
    return obj.left + obj.right;
  }
}, {
  pattern: {
    "type": A.eqv("sub"),
    "left": A.number,
    "right": A.number
  },
  action: function(obj) {
    return obj.left - obj.right;
  }
}];

// outputs 2
A.scan(rules, {
  "type": "add",
  "left": {
    "type": "add",
    "left": 1,
    "right": 2
  },
  "right": {
    "type": "sub",
    "left": 3,
    "right": 4
  }
});
        
A rule is an array of objects which has properties pattern and action.
Property "pattern" is an object of placeholders.
The first rule shown above represents that matches object which has property type whose value is "add" and property left and right whose value are numbers.
A function of property action is called with the object which is matched by the rule.
In the example shown above, the object of property left is passed to the action, and repleced by the result obj.left + obj.right = 1 + 2 = 3.
The scan method scans rules by depth-first and replaces matched objects.

The placehodlers are shown as follows.
See the reference.

NameDescription
eqv a value is equal to the given value
equal an object is equal to the given object by deep comparison
any a value is not null or undefined
number a value is a number
string a value is a string
object a value is an object and is not an array
array a value is an array
regex a value is matched to the given regex
range a value is in the given range
all all elements of an array are fulfilled by the given predicate
exists one of the elements of an array is fulfilled by the given predicate

Documentation

A document of Astraia is Here.