-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.js
34 lines (30 loc) · 1.18 KB
/
parser.js
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
// *
const handleMultiplicationSeparatedExpression = (expression) => {
const numbersString = expression.split("*");
const numbers = numbersString.map(noStr => +noStr);
const initialValue = 1.0;
const result = numbers.reduce((acc, no) => acc * no, initialValue);
return result;
};
// both * -
const handleMinusSeparatedExpression = (expression) => {
const numbersString = expression.split("-");
const numbers = numbersString.map(noStr => handleMultiplicationSeparatedExpression(noStr));
const initialValue = numbers[0];
const result = numbers.slice(1).reduce((acc, no) => acc - no, initialValue);
return result;
};
// * - +
const handlePlusSeparatedExpression = (expression) => {
const numbersString = expression.split("+");
const numbers = numbersString.map(noStr => handleMinusSeparatedExpression(noStr));
const initialValue = 0.0;
const result = numbers.reduce((acc, no) => acc + no, initialValue);
return result;
};
const handle = () => {
const expressionNode = document.getElementById("expression");
const resultNode = document.getElementById("result");
const result = handlePlusSeparatedExpression(expressionNode.value);
resultNode.value = String(result);
};