Skip to content

Instantly share code, notes, and snippets.

@tShwed
Created June 6, 2018 12:25
Show Gist options
  • Save tShwed/839661549fd01e04fd2936bd7bd68823 to your computer and use it in GitHub Desktop.
Save tShwed/839661549fd01e04fd2936bd7bd68823 to your computer and use it in GitHub Desktop.
/**
* S-Expression Calculator
*
*/
// Start the function using node calculator.js
// Process argument from the command line
let expr = process.argv[2];
// Function receives parsed expression from function below to determine add/multiply
function process_s_exp(parsed_exp) {
if (parsed_exp[0] === 'add') {
return process_s_exp(parsed_exp[1]) + process_s_exp(parsed_exp[2]);
} else if (parsed_exp[0] === 'multiply') {
return process_s_exp(parsed_exp[1]) * process_s_exp(parsed_exp[2]);
} else if (Array.isArray(parsed_exp[0])) {
return process_s_exp(parsed_exp[0]);
} else {
return parseInt(parsed_exp);
}
}
//Parsed through the string going character by character
function parse_s_expression(expr) {
let parsedExp = [[]];
let word = '';
//Used brackets/spaces to determine location of characters. Pushed characters to word to form add/multiply
for (char in expr) {
if (expr[char] === '(') {
parsedExp.push([]);
} else if (expr[char] === ')') {
if (word) {
parsedExp[parsedExp.length - 1].push(word);
word = '';
}
let temp = parsedExp.pop()
parsedExp[parsedExp.length - 1].push(temp);
} else if (expr[char] === ' ') {
if (word) {
parsedExp[parsedExp.length - 1].push(word)
word = ''
}
} else {
word += expr[char];
}
}
//Once word is formed, add/multiply is given to process_s_exp to calculate integers
return parsedExp[0];
}
console.log(process_s_exp(parse_s_expression(expr)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment