Skip to content

Instantly share code, notes, and snippets.

@hamiltondanielb
Created August 26, 2016 20:21
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 hamiltondanielb/5ce6505db40efc674656e7c4afdc386b to your computer and use it in GitHub Desktop.
Save hamiltondanielb/5ce6505db40efc674656e7c4afdc386b to your computer and use it in GitHub Desktop.
Calculator
function Calculator() {
}
Calculator.prototype.calc = function(str) {
var signs = ["*", "+","/"]; // signs in the order in which they should be evaluated
var funcs = [multiply, add, divide]; // the functions associated with the signs
var tokens = str.split(" "); // split the string into "tokens" (numbers or signs)
console.log(tokens)
for (var round = 0; round < signs.length; round++) { // do this for every sign
for (var place = 0; place < tokens.length; place++) { // do this for every token
if (tokens[place] == signs[round]) { // a sign is found
var a = parseFloat(tokens[place - 1]); // convert previous token to number
var b = parseFloat(tokens[place + 1]); // convert next token to number
var result = funcs[round](a, b); // call the appropriate function
tokens[place - 1] = result.toString(); // store the result as a string
tokens.splice(place--, 2); // delete obsolete tokens and back up one place
}
}
}
return tokens[0]; // at the end tokens[] has only one item: the result
function multiply(x, y) { // the functions which actually do the math
return x * y;
}
function add(x, y) { // the functions which actually do the math
return x + y;
}
function divide(x, y) { // the functions which actually do the math
return x / y;
}
}
Calculator.prototype.calcWithVars = function(inputList) {
// IMPLEMENT ME
}
function main() {
var calculator = new Calculator();
console.log("First Step");
console.log(calculator.calc("3 + 4 * 5 / 7"));
console.log("Second Step");
console.log(calculator.calc("( 3 + 4 ) * 5 / 7"));
console.log("Third Step");
console.log(calculator.calcWithVars(
["pi = 3",
"pizza = 9 * 9 * pi"]));
}
main();
// Please do not modify the following line.
var module = module || {};
module.exports = Calculator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment