Skip to content

Instantly share code, notes, and snippets.

@stormsweeper
Last active December 20, 2017 19:43
Show Gist options
  • Save stormsweeper/48b77d1515d4db4f3becd2487c3d9ee1 to your computer and use it in GitHub Desktop.
Save stormsweeper/48b77d1515d4db4f3becd2487c3d9ee1 to your computer and use it in GitHub Desktop.
var Calculator = (function(){
var first = 0;
var second = 0;
var current_op = null;
var result = null;
function update_screen(digits) {
$("#screen").text(digits);
}
function type_number(num) {
if (current_op !== null) {
if (second === null) {
second = 0;
}
second = (second * 10) + num;
update_screen(second);
} else {
// i.e. they hit =, then a number
if (result === first) {
result = null;
first = 0;
}
first = (first * 10) + num;
update_screen(first);
}
}
function type_clear() {
first = 0;
second = result = current_op = null;
update_screen(0);
}
function solve() {
if (current_op === "+") {
result = first + second;
}
else if (current_op === "-") {
result = first - second;
}
else if (current_op === "*") {
result = first * second;
}
else if (current_op === "/") {
result = first / second;
} else {
return;
}
current_op = null;
first = result;
second = null;
}
function type_operation(operation) {
if (current_op !== null) {
solve();
}
if (operation !== "=") {
current_op = operation;
}
update_screen(first);
}
return {"clear":type_clear,"number":type_number,"operation":type_operation};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment