This repository has been archived by the owner on Jun 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.js
86 lines (66 loc) · 1.79 KB
/
calculator.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
var store = document.getElementById("inputText");
var operations = ['+', '-', 'x', '/'];
var locked = false
function numberButton(val) {
if (locked) return
if (store.value == '0')
store.value = ""
if (store.value.length > 30) {
store.value = "Input too big!"
locked = true
}
store.value += val
}
function operatorButton(val) {
var input = store.value;
if (locked || input == "") return
if (operations.some(element => input.includes(element))) {
equalsButton()
}
var lastChar = input.substring(input.length - 1);
if (input != '' && operations.indexOf(lastChar) == -1) {
store.value += " " + val + " ";
} else if (input == '' && val == '-') {
store.value += " " + val + " ";
}
if (operations.indexOf(lastChar) > -1 && input.length > 1) {
store.value = input.substring(0, input.length - 1) + val;
}
}
function decimalButton() {
if (locked) return
if (!store.value.includes(".")) {
store.value += '.'
}
}
function equalsButton() {
var input = store.value.replaceAll("x", "*").split(' ')
if (input.length != 3) {
store.value = "Something is wrong!"
locked = true
return
}
var num1 = parseFloat(input[0])
var operation = input[1]
var num2 = parseFloat(input[2])
var res = 0.0
if (operation == '+') {
res = num1 + num2
} else if (operation == '-') {
res = num1 - num2
} else if (operation == '/') {
if (num2 != 0) {
res = num1 / num2
} else {
res = "NaN"
locked = true
}
} else if (operation == '*') {
res = num1 * num2
}
store.value = res.toString()
}
function resetButton() {
locked = false;
store.value = "0";
}