forked from a-a-ron/ps-github-foundations-github-copilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.js
More file actions
65 lines (56 loc) · 1.54 KB
/
controller.js
File metadata and controls
65 lines (56 loc) · 1.54 KB
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
"use strict";
exports.calculate = function (req, res) {
req.app.use(function (err, _req, res, next) {
if (res.headersSent) {
return next(err);
}
res.status(400);
res.json({ error: err.message });
});
var operations = {
add: function (a, b) {
return Number(a) + Number(b);
},
subtract: function (a, b) {
return a - b;
},
multiply: function (a, b) {
return a * b;
},
divide: function (a, b) {
return a / b;
},
power: function (a, b) {
return Math.pow(a, b);
},
// natural logarithm (ln) - uses only operand1
ln: function (a) {
return Math.log(Number(a));
},
};
if (!req.query.operation) {
throw new Error("Unspecified operation");
}
var operation = operations[req.query.operation];
if (!operation) {
throw new Error("Invalid operation: " + req.query.operation);
}
if (
!req.query.operand1 ||
!req.query.operand1.match(/^(-)?[0-9\.]+(e(-)?[0-9]+)?$/) ||
req.query.operand1.replace(/[-0-9e]/g, "").length > 1
) {
throw new Error("Invalid operand1: " + req.query.operand1);
}
// For unary ops like ln we don't require operand2; for others we do
if (req.query.operation !== "ln") {
if (
!req.query.operand2 ||
!req.query.operand2.match(/^(-)?[0-9\.]+(e(-)?[0-9]+)?$/) ||
req.query.operand2.replace(/[-0-9e]/g, "").length > 1
) {
throw new Error("Invalid operand2: " + req.query.operand2);
}
}
res.json({ result: operation(req.query.operand1, req.query.operand2) });
};