All files calculator.js

93.75% Statements 15/16
100% Branches 8/8
100% Functions 2/2
93.75% Lines 15/16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 371x       22x 22x 5x         17x 17x 1x           16x 16x 1x     15x 15x 5x 5x   10x              
module.exports = class Calculator {
  constructor() {}
 
  calculate(expression) {
    let pos = expression.indexOf("+");
    if (pos >= 0) {
      return (
        this.calculate(expression.substr(0, pos)) +
        this.calculate(expression.substr(pos + 1))
      );
    } else {
      pos = expression.indexOf("-");
      if (pos >= 0) {
        return (
          this.calculate(expression.substr(0, pos)) -
          this.calculate(expression.substr(pos + 1))
        );
      } else {
        // Remove ALL whitespaces
        expression = expression.replace(/\s+/g, "");
        if (expression === "") {
          return 0;
        }
 
        let num = Number(expression);
        if (!Number.isInteger(num)) {
          console.log("'" + expression + "' is not an integer");
          throw new Error("'" + expression + "' is not an integer");
        } else {
          return num;
        }
      }
    }
    return 0;
  }
};