Created
June 6, 2018 12:25
-
-
Save tShwed/839661549fd01e04fd2936bd7bd68823 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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