Skip to content

Instantly share code, notes, and snippets.

@tavurth
Created June 7, 2019 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tavurth/7afd1c5367a5ebbb79a34aae124c1e46 to your computer and use it in GitHub Desktop.
Save tavurth/7afd1c5367a5ebbb79a34aae124c1e46 to your computer and use it in GitHub Desktop.
const inputString = '(console.log (add 3 5 8 123 (minus 32 2 2 2)))';
const commands = {
'console.log': console.log,
inc(a, b) {
return Number.parseInt(a) + Number.parseInt(b);
},
dec(a, b) {
return Number.parseInt(a) - Number.parseInt(b);
},
add(...args) {
return args.reduce(this.inc);
},
minus(...args) {
return args.reduce(this.dec);
},
};
function findMatchingExpr(string, position = 0) {
let counter = 0;
while (position < string.length) {
switch (string[position]) {
case '(':
counter++;
break;
case ')':
counter--;
break;
default:
break;
}
if (counter === 0) {
return position + 1;
}
position++;
}
}
function extractBrace(string, pos = 0) {
const firstBrace = string.indexOf('(', pos);
const lastBrace = findMatchingExpr(string, firstBrace);
return string.slice(firstBrace, lastBrace);
}
function indexes(string, search) {
return string
.split('')
.reduce((acc, element, index) => (element === search ? acc.concat(index) : acc), []);
}
function extractBraces(string) {
const braces = [];
for (const index of indexes(string, '(')) {
braces.push(extractBrace(string, index));
}
return braces;
}
function runCommand(string) {
const [command, ...args] = string.slice(1, -1).split(' ');
return commands[command](...args);
}
function extractCommand(string) {
const braces = extractBraces(string).reverse();
for (const braceIndex in braces) {
const command = braces[braceIndex];
const result = runCommand(command);
braces.forEach((otherBrace, index) => {
braces[index] = otherBrace.replace(command, result);
});
}
}
extractCommand(inputString);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment