Skip to content

Instantly share code, notes, and snippets.

@captainkovalsky
Created May 22, 2024 21:01
Show Gist options
  • Save captainkovalsky/56f64ed8b566d7f992909b0d1721fa12 to your computer and use it in GitHub Desktop.
Save captainkovalsky/56f64ed8b566d7f992909b0d1721fa12 to your computer and use it in GitHub Desktop.
const input = `add(if(Q1;10;0);if(equals(Q2;"high");20;if(equals(Q2;"medium");10;0));Q3)`;
const data = {
Q1: true,
Q2: "medium",
Q3: 5,
};
const getParams = (str) => {
const [OPEN, CLOSED, DELIM] = ["(", ")", ";"];
let params = [];
let open = 0;
let expression = "";
for (let i = 0; i < str.length; i++) {
const char = str[i];
if (char === OPEN) {
open++;
}
if (char === CLOSED) {
open--;
}
if (i > 0 && i < str.length - 1) {
expression += char;
}
if (open === 1 && char === DELIM) {
//we reach end
params.push(expression.slice(0, expression.length - 1));
expression = "";
}
if (open === 0) {
params.push(expression);
}
}
return params;
};
const buildTree = (str) => {
let token = "";
const TOKENS = ["add", "if", "equals"];
if (str.startsWith(`"`)) {
return {
type: "string",
value: str.slice(1, str.length - 1),
};
}
if (str.startsWith("Q")) {
return {
type: "parameter",
value: str,
};
}
let number = parseInt(str, 10);
if (!Number.isNaN(number)) {
return {
type: "number",
value: number,
};
}
//parse functions
for (let i = 0; i < str.length; i++) {
let char = str[i];
token += char;
if (TOKENS.indexOf(token) !== -1) {
const params = getParams(str.slice(i + 1));
return {
type: token,
values: params.map((param) => buildTree(param)),
};
}
}
return result;
};
console.log(buildTree(input));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment