-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.js
executable file
·85 lines (68 loc) · 1.91 KB
/
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
//one way to start
// var Calculator = function(input) {
// var expression = input;
//
// this.expr = function() {
// };
//};
//another way to start
// var Calculator = function(input) {
// return {
// expr: function() {
// }
// };
// };
// //yet another way to start
var Calculator = function(input) {
var self = this,
expression = input;
function setExpr (newInput) {
expression = newInput;
}
self.setExpr = setExpr;
function expr () {
return expression;
}
self.expr = expr;
function addSync () {
if (!expression) return 0;
else if (expression.indexOf(',') === -1) return parseInt(expression);
return expression.split(',').reduce(function(prev,cur) { return parseInt(prev)+parseInt(cur); });
}
self.addSync = addSync;
function add (callback) {
callback(null, addSync());
}
self.add = add;
function diffSync () {
if (!expression) throw "Error in diffSync";
else if (expression.indexOf(',') === -1) throw "Error in diffSync";
return expression.split(',').reduce(function(prev,cur) { return parseInt(prev)-parseInt(cur); });
}
self.diffSync = diffSync;
function diff (callback) {
try {
var value = diffSync();
callback(null, value);
} catch(e) {
callback(e);
}
}
self.diff = diff;
function prod () {
if (!expression) throw "Error in prod";
else if (expression.indexOf(',') === -1) return parseInt(expression);
return expression.split(',').reduce(function(prev,cur) { return parseInt(prev)*parseInt(cur); });
}
self.prod = prod;
function div () {
if (!expression) throw "Error in div";
else if (expression.indexOf(',') === -1) return parseInt(expression);
return expression.split(',').reduce(function(prev,cur) { return parseInt(prev)/parseInt(cur); });
}
self.div = div;
return self;
};
// Calculator.prototype.expr = function() {
// };
module.exports = Calculator;