-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapple-calculator.js
106 lines (96 loc) · 2.67 KB
/
apple-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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
Calculates the input expression
*/
function calculate(text) {
var pattern = /\d*\.?\d+|\+|\-|\*|\/|\w*\(|\)|\^|\%/g; //matches nonzero digit sequences, operators and parentheses, g means global match
var tokens = text.match(pattern);
try {
var val = evaluate(tokens);
if(tokens.length > 0) throw("ill-formed expression");
return String(val);
} catch(err) {
return err;
}
}
/*
Reads the next operand in the expression
*/
function read_operand(array) {
var num = array.shift();
if(num == '(') {
num = evaluate(array);
if(array.shift() != ')') throw("missing close parenthesis");
}
if(num == 'sin(') {
num = Math.sin(evaluate(array));
if(array.shift() != ')') throw("missing close parenthesis");
}
if(num == '-') num += array.shift();
var out = parseFloat(num);
if(array[0] == '^') {
array.shift();
out = Math.pow(out,read_term(array))
}
if(isNaN(out)) {
throw("number expected");
}
else {
return out;
}
}
/*
Evaluates the expression
*/
function evaluate(array) {
if(array.length === 0) {
throw("missing operand");
}
var val = read_term(array);
while(array.length > 0) {
if(array[0] == ')') return val;
var oper = array.shift();
if($.inArray(oper,['+','-']) == -1) throw("unrecognized operator");
if(array.length === 0) throw("missing operand");
var temp = read_term(array);
if(oper == '+') val = val+temp;
if(oper == '-') val = val-temp;
}
return val;
}
function read_term(array){
if(array.length === 0) {
throw("missing operand");
}
var val = read_operand(array);
while(array.length > 0 & ['+','-'].indexOf(array[0]) == -1) {
if(array[0] == ')') return val;
var oper = array.shift();
if($.inArray(oper,['*','/','%']) == -1) throw("unrecognized operator");
if(array.length === 0) throw("missing operand");
var temp = read_operand(array);
if(oper == '*') val = val*temp;
if(oper == '/') val = val/temp;
if(oper == '%') val = val%temp;
}
return val;
}
/*
Sets up the HTML calculator
*/
/*
Calls setup when document is ready
*/
$(document).ready(function(){
var input = '';
$(".button").bind("click", function(event) {
input+=$(event.target).text()
$("#txtbox").text(input);
});
$('#equals').bind("click",function(){
$("#txtbox").text(calculate(input));
});
$('#c').bind("click",function(){
input = '';
$("#txtbox").text(input);
});
});