forked from woowacourse/javascript-calculator
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcalculator.js
More file actions
65 lines (65 loc) · 2.15 KB
/
Copy pathcalculator.js
File metadata and controls
65 lines (65 loc) · 2.15 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
import ScreenImpl from "./screen.js";
import BoardImpl from "./board.js";
import { calc } from "../../utils/utils.js";
class Calculator {
constructor($element) {
this.$element = $element;
this.clear = () => {
this.value = '';
this.oper = '';
this.prev = '';
};
this.setState = (value) => {
this.value = value;
this.screen.setState(value);
};
this.onClick = ({ type, value }) => {
switch (type) {
case 'Operator':
if (this.operatorPressed)
return;
this.operatorPressed = true;
this.prev = calc(this.prev, this.oper, this.value);
this.oper = value;
this.screen.setState(this.prev);
if (value === '=') {
this.operatorPressed = false;
}
this.value = '0';
break;
case 'Clear':
this.clear();
this.setState('0');
break;
case 'Number':
if (this.oper === '=')
this.clear();
if (this.value.length === 3)
break;
let newValue = this.value === '0' ? value : this.value + value;
if (!this.operatorPressed) {
this.setState(newValue);
break;
}
this.operatorPressed = false;
this.setState(value);
break;
default:
throw new Error('Operation fail');
}
};
this.value = '0';
this.prev = '';
this.oper = '';
this.operatorPressed = false;
this.screen = new ScreenImpl({
$element: this.$element.querySelector('#total'),
value: this.value
});
new BoardImpl({
$element: this.$element,
onClick: this.onClick
});
}
}
export default Calculator;