-
Notifications
You must be signed in to change notification settings - Fork 0
/
arithmetic.js
106 lines (88 loc) · 2.35 KB
/
arithmetic.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
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import divide from "./divide.js";
export default class Arithmetic {
constructor(drawCallBack) {
this.activeOperand = "left";
this.operands = {
left: randomInt(1, 9),
right: randomInt(1, 9),
};
this.operations = [
"+",
"−",
"×",
"÷",
];
this.operation = this.operations[randomInt(3)];
this.visualize = true;
this.draw = drawCallBack;
}
changeOperand(operand) {
if (operand) {
this.activeOperand = operand;
this.draw();
return;
}
this.activeOperand = this.activeOperand === "left" ? "right" : "left";
this.draw();
}
swapOperands() {
const left = this.operands.left;
this.operands.left = this.operands.right;
this.operands.right = left;
this.draw();
}
setOperand(value) {
this.operands[this.activeOperand] = parseInt(value);
this.draw();
}
switchOperation() {
const nextOperation = (this.operations.findIndex((i) => i === this.operation) + 1) % this.operations.length;
this.operation = this.operations[nextOperation];
this.draw();
}
setOperation(operation) {
this.operation = operation;
this.draw();
}
increaseActiveOperand() {
this.operands[this.activeOperand] = (this.operands[this.activeOperand] + 1) % 10;
this.draw();
}
decreaseActiveOperand() {
this.operands[this.activeOperand] = (this.operands[this.activeOperand] + 9) % 10;
this.draw();
}
getResult() {
switch (this.operation) {
case "+":
return this.operands.left + this.operands.right;
case "−":
return (this.operands.left - this.operands.right).toString().replace("-", "−");
case "×":
return this.operands.left * this.operands.right;
case "÷": {
if (this.operands.right === 0) {
return "?";
} else if (this.operands.left === 0) {
return 0;
}
return divide(this.operands.left, this.operands.right);
}
}
}
toggleVisualization() {
this.visualize = !this.visualize;
this.draw();
}
randomize() {
this.operands.left = randomInt(1, 9);
this.operands.right = randomInt(1, 9);
this.operation = this.operations[randomInt(3)];
this.draw();
}
}
function randomInt(from, to) {
const min = to ? from : 0;
const max = to ? to - from : from;
return Math.round(Math.random() * max) + min;
}