-
Notifications
You must be signed in to change notification settings - Fork 0
/
fancycalc.js
219 lines (202 loc) · 6.95 KB
/
fancycalc.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
var calculator = (function() {
exports = {};
var built_in_functions = {
abs: Math.abs,
acos: Math.acos,
asin: Math.asin,
atan: Math.atan,
atan2: Math.atan2, // 2 arg
ceil: Math.ceil,
cos: Math.cos,
exp: Math.exp,
floor: Math.floor,
log: Math.log,
max: Math.max, // multi-arg
min: Math.min, // multi-arg
pow: Math.pow, // 2 arg
round: Math.round,
sin: Math.sin,
sqrt: Math.sqrt,
};
var built_in_environment = {
pi: Math.PI,
e: Math.E,
};
function new_environment() {
var env = {};
for (var v in built_in_environment) {
env[v] = built_in_environment[v];
}
return env;
}
exports.new_environment = new_environment;
// if first token is t, consume it and return true
function read_token(t, tokens) {
if (tokens.length > 0 && tokens[0] == t) {
tokens.shift();
return true;
}
return false;
}
// builds parse tree for following BNF. Tree is either a number or
// or an array of the form [operator,tree,tree].
// <expression> ::= <term> | <expression> "+" <term> | <expression> "-" <term>
// <term> ::= <unary> | <term> "*" <unary> | <term> "/" <unary>
// <unary> ::= <factor> | "-" <factor> | "+" <factor>
// <factor> ::= <number> | "(" <expression> ")"
function parse_expression(tokens) {
var expression = parse_term(tokens);
while (true) {
if (read_token('+', tokens)) {
expression = ['+', expression, parse_term(tokens)];
}
else if (read_token('-', tokens)) {
expression = ['-', expression, parse_term(tokens)];
}
else break;
}
return expression;
}
function parse_term(tokens) {
var term = parse_exp(tokens);
while (true) {
if (read_token('*', tokens)) {
term = ['*', term, parse_exp(tokens)];
}
else if (read_token('/', tokens)) {
term = ['/', term, parse_exp(tokens)];
}
else break;
}
return term;
}
function parse_exp(tokens) {
var term = parse_unary(tokens);
while (true) {
if (read_token('^', tokens)) {
term = ['^', term, parse_unary(tokens)];
}
else break;
}
return term;
}
function parse_unary(tokens) {
if (read_token('-', tokens)) {
return ['neg', parse_factor(tokens)];
}
else if (read_token('+', tokens)) {}
return parse_factor(tokens);
}
function parse_factor(tokens) {
if (read_token('(', tokens)) {
var exp = parse_expression(tokens);
if (read_token(')', tokens)) {
return exp;
}
else throw 'Missing ) in expression';
}
else if (tokens.length > 0) {
var token = tokens.shift();
if (token.search(/[a-zA-Z_]\w*/) != -1) {
// variable name
if (read_token('(', tokens)) {
// a function call, parse the argument(s)
var args = [];
// code assumes at least one argument
while (true) {
args.push(parse_expression(tokens));
if (read_token(',', tokens)) continue;
if (read_token(')', tokens)) break;
throw "Expected comma or close paren in function call";
}
if (!(token in built_in_functions)) throw "Call to unrecognized function: " + token;
return ['call ' + token].concat(args);
}
// otherwise its just a reference to a variable
return token;
}
// only option left: a number
var n = parseFloat(token, 10);
if (isNaN(n)) throw 'Expected a number, got ' + String(token);
return n;
}
else throw 'Unexpected end of expression';
}
function evaluate(tree, environment) {
if (environment === undefined) environment = built_in_environment;
if (typeof tree == 'number') return tree;
else if (typeof tree == 'string') return environment[tree]; // might be undefined
else {
// expecting [operator,tree,...]
var args = tree.slice(1).map(function(subtree) {
return evaluate(subtree, environment);
});
if (tree[0].search(/^call /) != -1) {
// call of built-in function
var f = tree[0].slice(5);
f = built_in_functions[f];
if (f === undefined) throw "Unknown function: " + f;
return f.apply(undefined, args);
}
// otherwise its just an operator
else switch (tree[0]) {
case 'neg':
return -args[0];
case '+':
return args[0] + args[1];
case '-':
return args[0] - args[1];
case '*':
return args[0] * args[1];
case '/':
return args[0] / args[1];
case '^':
return Math.pow(args[0],args[1]);
default:
throw 'Unrecognized operator ' + tree[0];
}
}
}
exports.evaluate = evaluate;
function parse(text) {
// pattern matches integers, variable names, parens and the operators +, -, *, /
var pattern = /([0-9]*\.)?[0-9]+([eE][\-+]?[0-9]+)?|[a-zA-Z_]\w*|\+|\-|\*|\/|\^|\(|\)|\,/g;
var tokens = text.match(pattern);
return parse_expression(tokens);
}
exports.parse = parse;
function calculate(text,environment) {
if (environment === undefined) environment = built_in_environment;
try {
var tree = parse(text);
return evaluate(tree, environment);
}
catch (err) {
return err;
}
}
exports.calculate = calculate;
function setup_calc(div) {
$(document).ready(function(){
$('.numbutton').bind("click", function(event){
$('#output').text()+=$(event.target).text()
});
$('#equals').bind("click", function(){
expression=(String(calculate($('.output').val())));
$('#output').text(expression)
});
});
var input = $('<input></input>', {
type: 'text',
size: 50
});
var output = $('<div></div>');
var button = $('<button>Calculate</button>');
button.bind("click", function() {
output.html(String(calculate(input.val())));
});
$(div).append(input, button, output);
}
exports.setup_calc = setup_calc;
return exports;
}());