-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalc.js
73 lines (72 loc) · 2.14 KB
/
calc.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
const calc = document.querySelector('.calculation');
var result = document.querySelector('#result');
var prev = document.querySelector('#prev');
var answer = '';
calc.addEventListener('click', function(event) {
if(!event.target.classList.contains('but')) return;
let value = event.target.innerText;
switch(value){
case 'C':
result.innerText = '';
answer = '';
prev.innerText='';
break;
case '÷':
result.innerText += value;
answer += '/';
break
case '×':
result.innerText += value;
answer += '*';
break
case '√':
result.innerText += '√'+'(';
answer += 'Math.sqrt(';
break
case '^':
result.innerText += '^';
answer += '**';
break
case 'π':
result.innerText += 'π';
answer += 'Math.PI';
break
case '%':
result.innerText += '%';
answer += '*(1/100)';
break
case '( )':
if ((answer.split(')').join(', ').split('(').join(', ').split(', ').length-1) % 2 == 0){
answer += '(';
result.innerText +='(';
}else{
answer += ')';
result.innerText +=')';
}
break
case '|':
if (result.innerText.length > 1){
result.innerText = result.innerText.slice(0, result.innerText.length-1);
answer = answer.slice(0, answer.length-1);
}
else {
result.innerText = '';
answer = '';
}
break
case '=':
try{
prev.innerText = result.innerText;
result.innerText = eval(answer);
answer = eval(answer)
} catch(r){
result.innerText = 'error';
answer = ''
}
break
default:
result.innerText += value;
answer += value;
break
}
});