This repository has been archived by the owner on Jul 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
day1.js
106 lines (100 loc) · 2.87 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
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
//calculate: evaluate the the value of an arithmetical expression
function calculate(text) {
var pattern = /\d+(\.\d+)?|\+|\-|\*|\/|\(|\)/g;
var tokens = text.match(pattern);
try {
var num_open = 0;
var num_close = 0;
if(tokens==null) {
if(isNaN(parseFloat(text))) throw "Number Expected";
else return text;
}
for(var i=0;i<tokens.length;i++) {
if (tokens[i]=='(') num_open++;
if (tokens[i]==')') num_close++;
}
if(num_open!=num_close) throw "Ill-formed expression.";
var val = evaluate(tokens);
//if(tokens.length>0) throw "Ill-formed expression.";
if(isNaN(val)) throw "Number expected";
return String(val)
}
catch(err) {
return "Error: "+err;
}
}
//looks for integer as next item and handles for open parentheses
function read_operand(tokens) {
var first = tokens.shift();
if(first=="(") {
try {
if(tokens.indexOf(")")==-1) throw "Missing close-parentheses."
}
catch(err) {
return "Error: "+err;
}
var newInt = evaluate(tokens);
} else if(first=="-") {
var newInt = -1*parseFloat(tokens.shift());
}
else {
var newInt = parseFloat(first);
}
return newInt
}
//identifies operands and performs operations
function evaluate(tokens) {
try {
if(tokens.length<1) throw "Missing operand.";
}
catch(err) {
return "Error: "+err;
}
var value = read_operand(tokens);
if(isNaN(value)) return value;
while (tokens.length>0) {
var operator = tokens.shift();
if (operator==")") {
return value;
}
try {
if(operator!='+' && operator!='-' && operator!='*' && operator!='/') throw "Unrecognized operator.";
if(tokens.length<1) throw "Missing operand.";
}
catch(err) {
return "Error: "+err;
}
var temp = read_operand(tokens);
try {
if(operator=='+') {
value = value+temp;
} else if(operator=='-') {
value = value-temp;
} else if(operator=='*') {
value = value*temp;
} else if(operator=='/') {
value = value/temp;
}
if(isNaN(value)) throw "Number expected";
}
catch(err) {
return "Error: "+err;
}
}
return value;
}
function setup_calc(div) {
var input = $('<input></input>',{type: "text", size: 50});
var output = $('<div></div>', {class: "output"});
var button = $('<button>Calculate</button>');
button.bind('click', function(){
output.text(String(calculate(input.val())));
});
$(div).append(input,button,output);
}
$(document).ready(function() {
$('.calculator').each(function() {
//this refers to the div with class calculator
setup_calc(this);
});
});