-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise2.ts
101 lines (90 loc) · 2.88 KB
/
exercise2.ts
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
// script.ts
interface ICalculator {
add(a: number, b: number): number;
subtract(a: number, b: number): number;
multiply(a: number, b: number): number;
divide(a: number, b: number): number | string;
}
class BasicCalculator implements ICalculator {
add(a: number, b: number): number {
return a + b;
}
subtract(a: number, b: number): number {
return a - b;
}
multiply(a: number, b: number): number {
return a * b;
}
divide(a: number, b: number): number | string {
if (b === 0) {
return 'Error: Division by zero is not allowed.';
}
return a / b;
}
}
const calculator = new BasicCalculator();
let currentOperation: string | null = null;
let firstOperand: number | null = null;
let secondOperand: number | null = null;
function appendNumber(number: number) {
const display = document.getElementById('display') as HTMLInputElement;
display.value += number.toString();
}
function clearDisplay() {
const display = document.getElementById('display') as HTMLInputElement;
display.value = '';
firstOperand = null;
secondOperand = null;
currentOperation = null;
}
function performOperation(operation: string) {
const display = document.getElementById('display') as HTMLInputElement;
if (display.value === '') {
return;
}
if (firstOperand === null) {
firstOperand = parseFloat(display.value);
currentOperation = operation;
display.value += ' ' + operation + ' ';
} else if (currentOperation !== null) {
secondOperand = parseFloat(display.value.split(' ')[2]);
calculateResult();
firstOperand = parseFloat(display.value);
currentOperation = operation;
display.value += ' ' + operation + ' ';
}
}
function calculateResult() {
const display = document.getElementById('display') as HTMLInputElement;
if (display.value === '' || firstOperand === null || currentOperation === null) {
return;
}
const parts = display.value.split(' ');
if (parts.length < 3) {
return;
}
secondOperand = parseFloat(parts[2]);
let result: number | string;
switch (currentOperation) {
case '+':
result = calculator.add(firstOperand, secondOperand);
break;
case '-':
result = calculator.subtract(firstOperand, secondOperand);
break;
case '*':
result = calculator.multiply(firstOperand, secondOperand);
break;
case '/':
result = calculator.divide(firstOperand, secondOperand);
break;
default:
result = 'Unknown operation';
}
display.value = result.toString();
firstOperand = null;
secondOperand = null;
currentOperation = null;
}
// After saving the TypeScript file as script.ts, compile it to JavaScript using:
// tsc script.ts