Skip to content

Instantly share code, notes, and snippets.

@isapir
Last active May 11, 2019 01:27
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 isapir/caf0271f41c80712c837d0c75f5ad1bc to your computer and use it in GitHub Desktop.
Save isapir/caf0271f41c80712c837d0c75f5ad1bc to your computer and use it in GitHub Desktop.
/** Because `eval(q)` is too easy... Based on the post
https://www.linkedin.com/feed/update/urn:li:activity:6531594043288358912 */
/** Token types */
var TYPES = {
EOF : -1
,UNKNOWN : 0
,NUM : 1
,OP : 2
};
/** Returns the type of the character */
function getType(c) {
if (c == '-' || c == '+')
return TYPES.OP;
else if (c >= '0' && c <= '9')
return TYPES.NUM;
return TYPES.UNKNOWN;
}
/** Returns the next token from the given position */
function nextToken(input, pos){
if (pos >= input.length)
return { type: TYPES.EOF };
var start = pos;
var char = input[start];
var type = getType(char);
for (pos=start + 1; pos < input.length; pos++){
char = input[pos];
if (getType(char) != type)
break;
}
return {
type : type
,start : start
,end : pos - 1
,text : input.substring(start, pos)
};
}
/** Returns an array of tokens from the input string */
function parse(input) {
var tokens = [];
var token = nextToken(input, 0);
while (token.type != TYPES.UNKNOWN && token.type != TYPES.EOF) {
tokens.push(token);
token = nextToken(input, token.end + 1);
};
return tokens;
}
/** Parses the input string and calculates the total */
function calc(input) {
var tokens = parse(input);
var total = 0;
var op = "+";
for (var ix in tokens) {
var token = tokens[ix];
var type = token.type;
switch (token.type) {
case TYPES.OP:
if (token.text == "-")
op = "-";
else if (token.text == "+")
op = "+";
break;
case TYPES.NUM:
var val = parseInt(token.text);
if (op == "+")
total += val;
else if (op == "-")
total -= val;
break;
} // switch
} // for ix
return total;
}
/** Prints to console the input and its result */
function calculate(q){
console.log(`calculate("${q}") => ${calc(q)}`);
}
/** Runs the test examples */
function test(){
calculate("6+9-12");
calculate("1+2-3+4-5+6-7");
calculate("100+200+300");
calculate("1-2-0");
calculate("255");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment