Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
cleancalc - 3 layer architecture
function cleancalc_handler() {
// retrieve user input and clean it
var a; // to tell the difference between no number and 0
var pre_a = document.getElementById("number1").value;
if (pre_a == '') {
a = undefined; // try Number('') to see why I do this
} else {
a = Number(pre_a);
};
var b;
var pre_b = document.getElementById("number2").value;
if (pre_b == '') {
b = undefined;
} else {
b = Number(pre_b);
}
var operation;
var pre_operation = document.getElementById("operation").value;
if (pre_operation == '') {
operation = undefined;
} else {
operation = pre_operation;
}
// pass through logic as pure values
var result = cleancalc.operate(operation, a, b);
// draw result to dom
var outputbox = document.getElementById("output")
outputbox.innerHTML = result
}
var operate_button = document.getElementById("addButton");
operate_button.addEventListener("click", cleancalc_handler);
let cleancalc = require('./cleancalc');
let args = process.argv.slice(2);
let operation = args[0];
let a = Number(args[1]);
let b = Number(args[2]);
// a & b can converted to anything falsy
if (isNaN(a)) {
// consider throwing a real error here
a = false;
};
if (isNaN(b)) {
b = false;
};
let result = cleancalc.operate(operation, a, b);
console.log(result)
var cleancalc = {
lastResult: null,
add: function (arg1, arg2) {
return arg1 + arg2;
},
substract: function (arg1, arg2) {
return arg1 - arg2;
},
multiply: function (arg1, arg2) {
return arg1 * arg2;
},
devide: function (arg1, arg2) {
return arg1 / arg2;
},
operate: function (operation, arg1, arg2) {
let result = 0;
if (arg2) {
result = this[operation](arg1, arg2);
} else {
result = this[operation](arg1, this.lastResult);
};
this.lastResult = result;
return result;
}
};
try {
module.exports = calc;
} catch (err) {
console.log("your in the browser")
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- style and html from Radovan -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M"
crossorigin="anonymous">
<link rel="stylesheet" href="./publis/style.css">
<script type="text/javascript" src="cleancalc.js"></script>
</head>
<body>
<div class="container">
<div class="box">
<input type="text" id="number1">
<input type="text" id="number2">
<button type="button" id="addButton" class="btn btn-light">operation:</button>
<input type="text" id="operation">
</div>
<div class="box" id="output">
</div>
</div>
<script type="text/javascript" src="./cleancalc-handler-browser.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.