-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalc.js
More file actions
66 lines (60 loc) · 1.58 KB
/
calc.js
File metadata and controls
66 lines (60 loc) · 1.58 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Calculator {
constructor() {
this.currentValue = "";
this.previousValue = "";
this.operator = null;
}
clear() {
this.currentValue = "";
this.previousValue = "";
this.operator = null;
}
appendNumber(number) {
if (number === "." && this.currentValue.includes(".")) return;
this.currentValue += number.toString();
}
chooseOperator(operator) {
if (this.currentValue === "") return;
if (this.previousValue !== "") {
this.compute();
}
this.operator = operator;
this.previousValue = this.currentValue;
this.currentValue = "";
}
compute() {
let computation;
const prev = parseFloat(this.previousValue);
const current = parseFloat(this.currentValue);
if (isNaN(prev) || isNaN(current)) return;
switch (this.operator) {
case "+":
computation = prev + current;
break;
case "-":
computation = prev - current;
break;
case "*":
computation = prev * current;
break;
case "/":
computation = current === 0 ? "Error" : prev / current;
break;
default:
return;
}
this.currentValue = computation.toString();
this.operator = null;
this.previousValue = "";
}
getDisplayValue() {
return this.currentValue || this.previousValue || "0";
}
}
// Example usage:
// const calc = new Calculator();
// calc.appendNumber('5');
// calc.chooseOperator('+');
// calc.appendNumber('3');
// calc.compute();
// console.log(calc.getDisplayValue()); // "8"