Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Sorted it into tokens for simplicity
- var script = [
- "20","/","(","6","+","4",")","*","5","+","4"
- ];
- //Currently processed token
- var currentToken;
- //Index in the script
- var index = 0;
- //Get next token
- function nextToken()
- {
- index += 1;
- currentToken = script[index];
- }
- //Check if current token is the same as the one we expect
- function acceptToken(type)
- {
- if(type == "num")
- {
- if(!isNaN(currentToken))
- {
- return true;
- }
- }
- else if(type == currentToken)
- {
- return true;
- }
- return false;
- }
- //acceptToken but throw error if the currentToken is unexpected
- function expectToken(expected)
- {
- if(acceptToken(expected))
- {
- return true;
- }
- console.log("Error: invalid token");
- return false;
- }
- //Parse factor (in this case either a number or a bracket)
- function parseFactor()
- {
- if(acceptToken("num"))
- {
- var num = parseInt(currentToken);
- nextToken();
- return num;
- }
- else if(acceptToken("("))
- {
- nextToken()
- var num = parseSum();
- expectToken(")")
- nextToken()
- return num;
- }
- else
- {
- nextToken();
- console.log("Error: invalid token");
- }
- }
- //Parse either division or multiplication
- function parseTerm()
- {
- var f1 = parseFactor();
- while(currentToken == "*" || currentToken == "/")
- {
- if(currentToken == "*")
- {
- nextToken();
- f1 *= parseFactor();
- }
- else if(currentToken == "/")
- {
- nextToken();
- f1 /= parseFactor();
- }
- }
- return f1;
- }
- //Parse addition/subtraction
- function parseSum()
- {
- if(currentToken == "+" || currentToken == "-")
- {
- nextToken();
- }
- var p1 = parseTerm();
- while(currentToken == "+" || currentToken == "-")
- {
- if(currentToken == "+")
- {
- nextToken();
- p1 += parseTerm();
- }
- else if(currentToken == "-")
- {
- nextToken();
- p1 -= parseTerm();
- }
- }
- return p1;
- }
- function main()
- {
- currentToken = script[index];
- var result = parseSum();
- console.log(result);
- }
- main();
Add Comment
Please, Sign In to add comment