Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions api/controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ exports.calculate = function (req, res) {
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) {
Expand All @@ -46,12 +50,15 @@ exports.calculate = function (req, res) {
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);
// 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) });
Expand Down
12 changes: 12 additions & 0 deletions public/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ function calculate(operand1, operand2, operation) {
case "^":
uri += "?operation=power";
break;
case "ln":
uri += "?operation=ln";
break;
default:
setError();
return;
Expand Down Expand Up @@ -113,8 +116,17 @@ function signPressed() {
}

function operationPressed(op) {
// store operand1
operand1 = getValue();
operation = op;

// ln is a unary operator (natural log) — compute immediately using operand1
if (op === "ln") {
state = states.complete;
calculate(operand1, 0, operation);
return;
}

state = states.operator;
}

Expand Down
4 changes: 4 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@
<button class="btn" onClick="numberPressed(0)">0</button>
<button class="btn" onClick="decimalPressed()">.</button>
<button class="btn" onClick="operationPressed('+')">+</button>

<!-- New natural log (ln) unary operator button -->
<button class="btn" onClick="operationPressed('ln')">ln</button>

<button class="btn" onClick="operationPressed('^')">^</button>

<button class="btn span-4" onClick="equalPressed()">=</button>
Expand Down