showing results for - "logic for building calculator using javascript without using eval"
Luce
10 May 2018
1function parseCalculationString(s) {
2    // --- Parse a calculation string into an array of numbers and operators
3    var calculation = [],
4        current = '';
5    for (var i = 0, ch; ch = s.charAt(i); i++) {
6        if ('^*/+-'.indexOf(ch) > -1) {
7            if (current == '' && ch == '-') {
8                current = '-';
9            } else {
10                calculation.push(parseFloat(current), ch);
11                current = '';
12            }
13        } else {
14            current += s.charAt(i);
15        }
16    }
17    if (current != '') {
18        calculation.push(parseFloat(current));
19    }
20    return calculation;
21}
22
23function calculate(calc) {
24    // --- Perform a calculation expressed as an array of operators and numbers
25    var ops = [{'^': (a, b) => Math.pow(a, b)},
26               {'*': (a, b) => a * b, '/': (a, b) => a / b},
27               {'+': (a, b) => a + b, '-': (a, b) => a - b}],
28        newCalc = [],
29        currentOp;
30    for (var i = 0; i < ops.length; i++) {
31        for (var j = 0; j < calc.length; j++) {
32            if (ops[i][calc[j]]) {
33                currentOp = ops[i][calc[j]];
34            } else if (currentOp) {
35                newCalc[newCalc.length - 1] = 
36                    currentOp(newCalc[newCalc.length - 1], calc[j]);
37                currentOp = null;
38            } else {
39                newCalc.push(calc[j]);
40            }
41            console.log(newCalc);
42        }
43        calc = newCalc;
44        newCalc = [];
45    }
46    if (calc.length > 1) {
47        console.log('Error: unable to resolve calculation');
48        return calc;
49    } else {
50        return calc[0];
51    }
52}
53var calculateButton = document.getElementById('calculate'),
54    userInput = document.getElementById('userInput'),
55    result = document.getElementById('result');
56calculateButton.addEventListener('click', function() {
57    result.innerHTML = "The answer is " + calculate(parseCalculationString(userInput.value));
58});