This was one of the first assignments I created in my bootcamp. It was quite fun and challenging at first to build. I struggled for a while, but I managed to pull it all together by simplifying some of the more complicated logic (for example, limiting the calculator to single, non-chained computations).
The core of this calculator lives in calculator.js
. Below is an overview of how it works so you (or future readers) can quickly understand the flow:
display
– the DOM element that shows the current input/result.operation
– a string that accumulates all characters the user has typed (digits, operators, decimals, minus-sign, etc.). This is eventually evaluated by eval()
.firstNumbers
/ secondNumbers
– convenience strings holding the numbers on the left and right side of the current operator. They are used mainly for what is shown on-screen while typing.operatorFLag
– true once an operator has been entered and we’re now typing the second operand.decimalFlag
– guards against multiple decimals in the same number.negativeFlag
– tracks whether the first number started with a minus sign.calculationFlag
– becomes true right after pressing =
so we know a new number should replace (not append to) the current result.showValue(input)
– called by every button. It branches based on what was clicked:
+
, -
, x
, /
)0-9
)addDecimal()
– safely appends a .
only if the current operand doesn’t already contain one.calculate()
– evaluates operation
using eval()
(after replacing x
with *
) and then resets flags so a fresh calculation can start.deleteResult()
– the “C” (clear) button. Resets everything including the flags and the display.7
→ showValue(7)
appends to operation
("7"
) and updates display
.+
→ showValue('+')
sets operatorFLag = true
, stores current operator, and updates operation
("7+"
).3
→ because operatorFLag
is true
, the digit goes into secondNumbers
and display
now shows 3
.=
→ calculate()
detects there was no x
, so it simply does eval("7+3")
, sets operation = "10"
, puts 10
on screen, and prepares for the next entry.3 + 2 + 4
).=
.eval()
with a small expression parser to avoid security concerns.keydown
events.firstNumbers/secondNumbers
into an array or using a finite-state machine.Feel free to tweak or extend this explanation as the project evolves! :)