-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay1.js
97 lines (85 loc) · 2.75 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
var calculator = (function () {
function calculate(text) {
//var txt = $('#text');
//var val = txt.val();
var pattern = /\d+|\+|\-|\*|\/|\(|\)/g;
var tokens = text.match(pattern);
try{
var val = evaluation(tokens)
if (tokens.length > 0){
throw "ill-formed expression"; //throw New Error "message" <-something like that
}
return String(val);
}
catch(err)
{
return err; //as in error message printed as an error
}
return JSON.stringify(tokens);
//return text;
}
function read_operand(tokens){
//var num_string = tokens.shift();
var operand_string = tokens.shift();
if (operand_string == "(") {
return evaluation(tokens, true);
}
if (operand_string == "-"){
var negate = read_operand(tokens);
return 0-negate;
}
var num = parseInt(operand_string);
if (isNaN(num)){
throw "number expect";
}
else {
return num;
}
}
//subexpression is boolean
//true if evaluating inside ()
function evaluation(tokens, subexpression){
subexpression = subexpression || false;
if (tokens.length == 0){
throw "missing operand";
}
var value = read_operand(tokens);
while (tokens.length > 0){
var operator = tokens.shift();
if (operator == ")" && subexpression){
return value;
}
if (["+","-","*","/"].indexOf(operator) == -1 ){
throw "unrecognized operator";
}
if (tokens.length == 0){
throw "missing operand";
}
var temp = read_operand(tokens);
var ops = {"+": function add(x,y){return x+y},
"-": function sub(x,y){return x-y},
"*": function mul(x,y){return x*y},
"/": function divi(x,y){return x/y} };
value = ops[operator](value,temp);
}
return value;
}
function setup(div) {
var input = $('<input></input>', {type: 'text', size: 50});
var output = $('<div></div>');
var button = $('<button>Calculate</button>');
$(div).append(input,button,output);
button.on('click', function (event) {
output.text(calculate(input.val()));
});
}
return {
calculate: calculate,
setup: setup
};
})();
$(document).ready(function () {
$('.calc').each(function () {
calculator.setup(this);
});
});