This one really has me scratching my head.
I'm building a calculator using JavaScript as an exercise. Said calculator is up and running here on Codepen. In the lower left you will see a "+-" button, which simply takes the content of the input field, and reverses it's sign (positive becomes negative, negative becomes positive.) Then when the user presses an operation button this is pulled and used in the calculation. Simple right?
The function which actually changes the sign is as follows:
function toggleSign() {
if(getCurrentDispVal()[0] === "-") {
currentNumStr = currentNumStr.slice(1, currentNumStr.length);
} else {
currentNumStr = "-" + currentNumStr;
}
updateDisplay(currentNumStr);
}
and is called in just one place, a function which takes input from the user and decides what to do with it:
function useInput(input) {
if(input.match(/(\d|\.)/)) {
handleDigitInput(input);
} else if(input.match(/(X|\/|-|\+)/)) {
handleBinaryOperation(input);
} else if(input.match(/=/)) {
handleEqualsOperation();
} else if(input.match(/^c$/)) {
clearCurrentNumStr();
} else if(input.match(/^ac$/)) {
allClear();
} else if(input.match(/^shorten$/)) {
shortenCurrentNumStr();
} else if(input.match(/^plusmin$/)) {
toggleSign();
}
}
Now sometimes, and only sometimes, this works as expected. For instance, enter the following: 1 on keyboard, not the screen Click the "+-" button + on keyboard 5 on keyboard enter on keyboard
Sometimes this runs properly, and spits "4" as the result. Sometimes, and this is baffling me, when you hit enter it flips the sign on "5" making it "-5" and then returns "-6" as the answer." I've done some checking and can see that when this occurs, in the useInput function both the /=/ and /^plusmin$/ conditionals are being triggered. Thus toggleSign is being called prior to handleEqualsOperation and this is lousing up the results. Strangely, if you don't use the keyboard, and just click the screen buttons directly, this problem doesn't occur.
I'm at a loss here. There doesn't seem to be any pattern as to when this occurs, and I'm using the same input above over and over. I don't understand why this is occurring, and why it isn't occurring consistently.