Skip to content

Instantly share code, notes, and snippets.

@JSRossiter
Created August 20, 2017 06:30
Show Gist options
  • Save JSRossiter/9e0745015ca82ded43a366a386e1f786 to your computer and use it in GitHub Desktop.
Save JSRossiter/9e0745015ca82ded43a366a386e1f786 to your computer and use it in GitHub Desktop.
const input = [
"AND",
["<", "var1", "var2"],
[
"OR",
[">", "var3", "var4"],
["==", "var5", "var6"]
]
];
const result = "var1 < val2 AND (var3 > val4 OR val5 == val6)";
function stringify(array, depth) {
let left = '';
let right = '';
const operator = array[0];
if (operator === "AND" || operator === "OR") {
left = stringify(array[1], 1);
right = stringify(array[2], 1);
if (depth) {
left = '(' + left;
right += ')';
}
} else {
left = array[1];
right = array[2];
}
return `${left} ${operator} ${right}`;
}
function changeNames(input) {
return input.replace(/var[2,4-6]/g, (match) => {
return match.replace('r', 'l');
})
}
const output = changeNames(stringify(input));
console.log(output);
console.log(output === result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment