const Splitter = require("split-tools");
var text = "x > 5 && (y == 7.5) || sin(Math.PI*a/360) || true";
const splitter = new Splitter({
matchers: {
function: /\s*([a-z]\w*)\(\s*(.*)\s*\)/g,
bracket: /\(\s*(.*)\s*\)/g,
operator: /\s*(\>|\<|\=\=|\!\=|\&\&|\|\||\+|\-|\*|\/|\%)\s*/g,
variable: /\s*([a-z][\w\.]*)\s*/gi,
sting: /\s*\"(.*?)\"\s*/gi,
boolean: /\s*(true|false)\s*/gi,
value: /\s*(\d[\d\.]*)\s*/gi
}
});
const tree = {
"brackets": ["function", "bracket", "operator", "variable", "sting", "boolean", "value"]
};
function subSplit(id, text) {
console.log("subSplit:", id, "[", text, "]");
if(tree[id] && tree[id].length)
return splitter.process(text, tree[id]);
return text;
}
splitter.addParser("function",(match,name,body)=>{
return {
type: "function",
name: name,
body: subSplit("brackets", body)
};
});
splitter.addParser("bracket",(match,body)=>{
return {
type: "bracket",
body: subSplit("brackets", body)
};
});
splitter.addParser("operator",(match,body)=>{
return {
type: "operator",
body: body
};
});
splitter.addParser("variable",(match,body)=>{
return {
type: "variable",
body: body
};
});
splitter.addParser("string",(match,body)=>{
return {
type: "string",
body: body
};
});
splitter.addParser("boolean",(match,body)=>{
return {
type: "boolean",
body: !!body
};
});
splitter.addParser("value",(match,body)=>{
return {
type: "value",
body: +body
};
});
const list = splitter.process(text, tree.tags);
console.log("\n\nresult:\n",JSON.stringify(list, null, ' '));