Reputation: 2496
I'm making home page using AngularJS and there is arithmetic function.
<div class="input-form">
<input ng-model="value1" id="value1" type="number" />
<input ng-model="value2" id="value2" type="number" />
<input ng-model="value3" id="value3" type="number" />
<input ng-model="value4" id="value4" type="number" />
<input ng-model="value5" id="value5" type="number" />
</div>
<div class="equation-form">
<input ng-model="equation" type="text" />
</div>
<button class="yellow" ng-click="calculate()">Calculation</button>
If user press "Calculation" button after input arithmetic equation to equation field, need to calculate result and send server.
Equation input like as "1 + 2 - 3 * 4 + 5"
.
1,2,3,4,5 values means input value named as value1, value2, value3, value4, value5
Here is what I tried to achieve the calculation:
scope.calculate = function () {
let equation = scope.equation.replace(/\s+/g, ''); // remove spaces
if (!/^\d+(?:[+-]\d+)*$/.test(expression)) { //
console.error('wrong equation');
return;
}
let fieldIndexes = expression.split(/(?=[+-])/); // split expression
if (fieldIndexes) {
fieldIndexes.forEach(x => {
// process calculation
});
}
}
Function is done in two steps:
First, split equation to [ 1, +2, -3, *4, 5 ].
Second, calculate splited equation.
But now, I've only split by "-", "+".
If user input "1 + 2 - 3 + 4 - 5"
, current function split it to "1", "+2", "-3", "+4", "-5"
.
How can I split string by "-", "+", "*", "/" symbol?
Any suggestions?
Upvotes: 0
Views: 171
Reputation: 688
Well, I wrote something that does not use RegExp.
class Operation {
constructor(data) {
this.data = data;
}
result(items = null) {
for (var i = 0; i < items.length; i++) {
items[i] = items[i].split(this.data.op);
if (this.data.next) {
items[i] = this.data.next.result(items[i]);
}
items[i] = items[i].reduce(this.data.reducer);
}
return items;
}
}
function calculate(expr) {
var mult = new Operation({ op: "*", next: null, reducer: (f, l) => { return parseInt(f) * parseInt(l) } });
var div = new Operation({ op: "/", next: mult, reducer: (f, l) => { return parseInt(f) / parseInt(l) } });
var sub = new Operation({ op: "-", next: div, reducer: (f, l) => { return parseInt(f) - parseInt(l) } });
var add = new Operation({ op: "+", next: sub, reducer: (f, l) => { return parseInt(f) + parseInt(l) } });
return add.result([expr.replace(/\s+/g, "")])[0];
}
You supply the calculate function with the arithmetic expression and it returns the result for you. Each operation layer passes the operands - "items" - to the next higher order operation until it reaches the last one (which here is multiplication).
Example: console.log(calculate("6 * 5 - 2"));
Adding brackets now should be simple.
Does that help?
Upvotes: 0