Skip to content

Instantly share code, notes, and snippets.

@e-mihaylin
Created October 4, 2018 11:10
Show Gist options
  • Save e-mihaylin/e876db6f6e5a9ffdeb6f6ad6e1807958 to your computer and use it in GitHub Desktop.
Save e-mihaylin/e876db6f6e5a9ffdeb6f6ad6e1807958 to your computer and use it in GitHub Desktop.
const calc = s => run(s.replace(/\s+/g, '').split``);
const run = s => {
let result = term(s);
while (peek(s) == '+' || peek(s) == '-') {
if (get(s) == '+') result += term(s);
else result -= term(s);
}
return result;
};
const term = s => {
let result = factor(s);
while (peek(s) == '*' || peek(s) == '/') {
if (get(s) == '*') result *= factor(s);
else result /= factor(s);
}
return result;
};
const peek = s => s[0] || '';
const get = s => s.shift();
const factor = s => {
if (peek(s) === "-") {
get(s);
return -1 * factor(s);
} else if(!isNaN(peek(s)))
return makeNumber(s);
else if(peek(s) === "(") {
get(s);
const number = run(s);
get(s);
return number;
}
};
const makeNumber = s => {
var result = '';
while(/[0-9\.]/.test(peek(s))) result += get(s);
return Number(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment