-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathcontroller.js
More file actions
45 lines (36 loc) · 1.3 KB
/
controller.js
File metadata and controls
45 lines (36 loc) · 1.3 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
'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 },
// 'modulo': function(a, b) { return a % b },
'power': function(a, b) { return Math.pow(a, b) }
};
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);
}
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) });
};