|
| 1 | +const defaultResult = 0; |
| 2 | +let currentResult = defaultResult; |
| 3 | +let logEntries = []; |
| 4 | + |
| 5 | +// Gets input from input field |
| 6 | +function getUserNumberInput() { |
| 7 | + return parseInt(usrInput.value); |
| 8 | +} |
| 9 | + |
| 10 | +// Generates and writes calculation log |
| 11 | +function createAndWriteOutput(operator, resultBeforeCalc, calcNumber) { |
| 12 | + const calcDescription = `${resultBeforeCalc} ${operator} ${calcNumber}`; |
| 13 | + outputResult(currentResult, calcDescription); // from vendor file |
| 14 | +} |
| 15 | + |
| 16 | +function writeToLog( |
| 17 | + operationIdentifier, |
| 18 | + prevResult, |
| 19 | + operationNumber, |
| 20 | + newResult |
| 21 | +) { |
| 22 | + const logEntry = { |
| 23 | + operation: operationIdentifier, |
| 24 | + prevResult: prevResult, |
| 25 | + number: operationNumber, |
| 26 | + result: newResult |
| 27 | + }; |
| 28 | + logEntries.push(logEntry); |
| 29 | + console.log(logEntries); |
| 30 | +} |
| 31 | + |
| 32 | +function add() { |
| 33 | + const enteredNumber = getUserNumberInput(); |
| 34 | + const initialResult = currentResult; |
| 35 | + currentResult += enteredNumber; |
| 36 | + createAndWriteOutput('+', initialResult, enteredNumber); |
| 37 | + writeToLog('ADD', initialResult, enteredNumber, currentResult); |
| 38 | +} |
| 39 | + |
| 40 | +function subtract() { |
| 41 | + const enteredNumber = getUserNumberInput(); |
| 42 | + const initialResult = currentResult; |
| 43 | + currentResult -= enteredNumber; |
| 44 | + createAndWriteOutput('-', initialResult, enteredNumber); |
| 45 | + writeToLog('SUBTRACT', initialResult, enteredNumber, currentResult); |
| 46 | +} |
| 47 | + |
| 48 | +function multiply() { |
| 49 | + const enteredNumber = getUserNumberInput(); |
| 50 | + const initialResult = currentResult; |
| 51 | + currentResult *= enteredNumber; |
| 52 | + createAndWriteOutput('*', initialResult, enteredNumber); |
| 53 | + writeToLog('MULTIPLY', initialResult, enteredNumber, currentResult); |
| 54 | +} |
| 55 | + |
| 56 | +function divide() { |
| 57 | + const enteredNumber = getUserNumberInput(); |
| 58 | + const initialResult = currentResult; |
| 59 | + currentResult /= enteredNumber; |
| 60 | + createAndWriteOutput('/', initialResult, enteredNumber); |
| 61 | + writeToLog('DIVIDE', initialResult, enteredNumber, currentResult); |
| 62 | +} |
| 63 | + |
| 64 | +addBtn.addEventListener('click', add); |
| 65 | +subtractBtn.addEventListener('click', subtract); |
| 66 | +multiplyBtn.addEventListener('click', multiply); |
| 67 | +divideBtn.addEventListener('click', divide); |
0 commit comments