-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday1.js
73 lines (69 loc) · 2.14 KB
/
day1.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
function read_operand(tokenArray) {
var operand = tokenArray.shift();
if (operand == '(') {
operand = evaluate(tokenArray)
}
operand = parseInt(operand)
if (isNaN(operand)){
throw 'Number expected';
}
else {
return operand;
}
}
function evaluate(tokenArray) {
if (tokenArray.length<1) {
throw 'Missing operand';
}
var value = read_operand(tokenArray);
while (tokenArray.length>=1) {
var operator = tokenArray.shift();
var valid_operators = ['+', '-','*','/',')','('];
if ($.inArray(operator, valid_operators) == -1){ //jQuery.inArray is used to check if the operator is valid. If perator is not in the array valid_operators, inArray returns -1.
throw 'Invalid operator';
}
if (operator == ')') {
return value;
}
var tempOperand = read_operand(tokenArray);
//The following section is porbably not the best way to do this- it seems repetitive. I should replace this at some point.
if (operator == "+") {
value = value + tempOperand;
}
if (operator == "-") {
value = value - tempOperand;
}
if (operator == "*") {
value = value * tempOperand;
}
if (operator == "/") {
value = value / tempOperand;
}
}
return value
}
function calculate(text) {
var pattern = /\d+|\+|\-|\*|\/|\(|\)/g;
var tokens = text.match(pattern);
var value = evaluate(tokens);
if (tokens.length>0){
throw 'Ill formed expression';
}
else {
return value;
}
}
// function setup_calc(div) {
// var input =$('<input></input>', {type: "text", size:50});
// var output = $('<div></div>');
// var button = $('<button>Calculate</button>');
// button.bind("click", function() {
// output.text(calculate(input.val()));
// });
// $(div).append(input,button,output);
// }
// $(document).ready(function(){
// $('.calculator').each(function() {
// setup_calc(this);
// });
});