Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Answer #383

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
210 changes: 210 additions & 0 deletions calculator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
// ====================================================================================================
// HELPERS
// ====================================================================================================
hasWhitespace = (str) => /\s/g.test(str);

isNumeric = (str) =>
str === 0 || (!hasWhitespace(str) && !isNaN(parseFloat(str)));

// ====================================================================================================
// HTML
// ====================================================================================================

// Cache html elements
const inputField = document.querySelector("input");
const h2 = document.querySelector("h2");

// Add listeners to all buttons
document
.querySelectorAll("button")
.forEach((button) => button.addEventListener("click", onButton));

// Listen to key press
document.addEventListener("keypress", onKey);

// Listen to input
inputField.addEventListener("input", onInput);

// Button event
function onButton(event) {
let button = event.target.id;
inputField.value += button;
inputField.dispatchEvent(new Event("input"));
}

// Key event
function onKey(event) {
if (event.key === "Enter") {
inputField.value += "=";
inputField.dispatchEvent(new Event("input"));
}
}

// Input event
function onInput(event) {
event.target.value = calculator.processInput(event.target.value);
h2.innerHTML = isNumeric(calculator.intermediate)
? calculator.intermediate
: "";
}

// ====================================================================================================
// CALCULATOR
// ====================================================================================================
let calculator = new Calculator();

function Calculator() {
//this.entries = [];
this.intermediate;
this.lastResult;

this.leftOperand;
this.lastOperator;
this.rightOperand;

this.processInput = function (input) {
let filtered = filterInput(input);
return filtered;
};

this.reset = function () {
this.entries = [];
this.intermediate = undefined;
this.lastOperator = undefined;
this.rightOperand = undefined;
};

this.operators = {
"+": function (a, b) {
return a + b;
},
"-": function (a, b) {
return a - b;
},
"*": function (a, b) {
return a * b;
},
"/": function (a, b) {
return a / b;
},
};

hasOperator = (str) => {
return str.split("").some((char) => isOperator(char));
};

isOperator = (op) => {
return Object.keys(this.operators).includes(op);
};

// TODO: Handle processing intermediate with decimals as entry # > 1
// TODO: Handle negatives as the first input
// TODO: Handle floating point precision errors
filterInput = (input) => {
let entries = [];

if (isNumeric(this.lastResult)) {
if (!input || !input.includes("=")) {
this.lastResult = undefined;
}
else if (isNumeric(input.slice(-1)) || input.slice(-1) === '.') {
input = input.slice(-1);
this.lastResult = undefined;
}
}

[...input].forEach((char) => {
let lastEntry = entries.at(-1);

// if this is the first entry
if (!lastEntry) {
switch (true) {
case isNumeric(char):
entries.push(char);
break;
case char === ".":
entries.push("0.");
break;
}
this.leftOperand = parseFloat(char);
}
// rest of the entries
else {
switch (true) {
case isNumeric(char):
// # or #.
if (isNumeric(lastEntry) || lastEntry === ".") {
entries[entries.length - 1] += char;

if (entries.length > 1) {
this.rightOperand = parseFloat(entries[entries.length - 1]);

if (entries.length == 3)
this.leftOperand = parseFloat(entries[0]);
processIntermediate();
}
else {
this.leftOperand = parseFloat(entries[entries.length - 1]);
}
}
// operator
else if (isOperator(lastEntry)) {
entries.push(char);
this.rightOperand = parseFloat(char);
processIntermediate();
}
break;
case char === ".":
// operator
if (isOperator(lastEntry)) {
entries.push("0.");
this.rightOperand = parseFloat(char);
processIntermediate();
}
// # but NOT #.
else if (isNumeric(lastEntry) && !lastEntry.includes(".")) {
entries[entries.length - 1] += char;
}
break;
case isOperator(char):
this.intermediate = undefined;
// operator
if (isOperator(lastEntry)) {
entries[entries.length - 1] = char;
this.lastOperator = char;
}
// # or #.
else if (isNumeric(lastEntry) || lastEntry === ".") {
entries.push(char);
this.lastOperator = char;
}
break;
case char === "=":
if (isNumeric(this.intermediate)) {
this.lastResult = this.intermediate;
this.intermediate = undefined;
} else if (isNumeric(this.lastResult)) {
processIntermediate();
this.lastResult = this.intermediate;
this.intermediate = undefined;
}
break;
}
}
});

return isNumeric(this.lastResult) ? this.lastResult : entries.join("");
};

processIntermediate = () => {
if (!isNumeric(this.leftOperand) || !this.lastOperator || !isNumeric(this.rightOperand))
this.intermediate = undefined;
else {
this.intermediate = this.operators[this.lastOperator](
this.leftOperand,
this.rightOperand
);
this.leftOperand = this.intermediate;
}
};
}
50 changes: 50 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>100Devs Calculator - Johnny J Wu</title>
<link rel="stylesheet" href="style.css">
</head>

<body>
<div class="container center">
<div class="calculator">
<input id="textField" type=text>
<h2></h2>
<div class="container">
<div class="container">
<button id="7">7</button>
<button id="8">8</button>
<button id="9">9</button>
<button id="/">/</button>
</div>

<div class="container">
<button id="4">4</button>
<button id="5">5</button>
<button id="6">6</button>
<button id="*">x</button>
</div>

<div class="container">
<button id="1">1</button>
<button id="2">2</button>
<button id="3">3</button>
<button id="+">+</button>
</div>

<div class="container">
<button id="0">0</button>
<button id=".">.</button>
<button id="=">=</button>
<button id="-">-</button>
</div>
</div>
</div>
</div>
<script src="calculator.js"></script>
</body>

</html>
89 changes: 89 additions & 0 deletions style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
* {
box-sizing: border-box;
}

/* Chrome, Safari, Edge, Opera */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}

/* Firefox */
input[type=number] {
-moz-appearance: textfield;
}

.container {
display: flex;
}

.container.center {
justify-content: center;
align-items: center;
height: 100vh;
}

button {
background-color: white;
border: none;
border-radius: 50%;
cursor: pointer;
}

button:hover {
opacity: 0.8;
}

button:active {
filter: brightness(0.8);
}

.calculator {
background-color: black;
border-radius: 2rem;
width: 400px;
padding: 2rem;
}

.calculator input {
background-color: white;
border: none;
font-size: 2rem;
margin: 0;
max-height: 5rem;
outline: none;
padding: 1rem;
text-align: right;
width: 100%;
overflow-wrap: break-word;
}

.calculator h2 {
background-color: white;
color: grey;
line-height: 2rem;
margin: 0;
margin-bottom: 2rem;
padding: 0 1rem 1rem 1rem;
text-align: right;
height: 3rem;
}


.calculator button {
aspect-ratio: 1;
width: 20%;
font-weight: bold;
font-size: 2rem;
}

.calculator>.container {
flex-direction: column;
gap: 1rem;
}

.calculator>.container .container {
justify-content: space-between;
align-content: space-between;
}