|
| 1 | +"use strict"; |
| 2 | +document.addEventListener('DOMContentLoaded', () => { |
| 3 | + const btns = document.querySelectorAll("[data-value]"); |
| 4 | + const historyElement = document.querySelector(".computation-history"); |
| 5 | + // let screenElement = document.querySelector("[data-screenElement]") as HTMLElement; |
| 6 | + // const screenElement = document.querySelector("[data-screenElement]") as HTMLDivElement & { innerText: string} | {innerText: number}; |
| 7 | + const screenElement = document.querySelector("[data-screen]"); |
| 8 | + console.log(screenElement); |
| 9 | + const historyBtn = document.querySelector(".history-btn"); |
| 10 | + const slidingPart = document.querySelector(".sliding-part"); |
| 11 | + const computationHistoryParent = document.querySelector(".computation-history-parent"); |
| 12 | + const operators = document.querySelectorAll("[data-operator]"); |
| 13 | + const clearHistoryBtn = document.querySelector(".clear-history-btn"); |
| 14 | + const minus = document.querySelector(".minus"); |
| 15 | + console.log(minus); |
| 16 | + let currentExpression; |
| 17 | + clearHistoryBtn.addEventListener("click", () => { |
| 18 | + historyElement.innerHTML = ""; |
| 19 | + }); |
| 20 | + document.addEventListener("keydown", handleKeyPress); |
| 21 | + // Add this at the beginning of your script |
| 22 | + window.addEventListener("DOMContentLoaded", () => { |
| 23 | + const history = getHistoryFromLocalStorage(); |
| 24 | + createHistoryList(history, historyElement); |
| 25 | + }); |
| 26 | + function handleKeyPress(event) { |
| 27 | + const key = event.key; |
| 28 | + const button = document.querySelector(`[data-value="${key}"]`); |
| 29 | + if (button) { |
| 30 | + button.click(); // Trigger the click event for the corresponding button |
| 31 | + } |
| 32 | + if (event.code === "Backspace") { |
| 33 | + let newArray = data.slice(ZERO, -1); |
| 34 | + screenElement.innerText = newArray.join(""); |
| 35 | + data = newArray; |
| 36 | + if (screenElement.innerText === "") { |
| 37 | + screenElement.innerText = String(ZERO); |
| 38 | + } |
| 39 | + } |
| 40 | + if (event.code === "Enter") { |
| 41 | + userClicksOnEqualButton("="); |
| 42 | + } |
| 43 | + } |
| 44 | + const operatorRegex = /[\/*\-+]/; |
| 45 | + const ZERO = 0; |
| 46 | + const ZERO_DOT = "0."; |
| 47 | + const HISTORY_LIMIT = 10; |
| 48 | + // const history = []; |
| 49 | + historyBtn.addEventListener("click", () => { |
| 50 | + slidingPart.classList.toggle("slide"); |
| 51 | + computationHistoryParent.classList.toggle("visility"); |
| 52 | + }); |
| 53 | + let data = []; |
| 54 | + btns.forEach((btn) => { |
| 55 | + btn.addEventListener("click", function (e) { |
| 56 | + let buttonValue = e.target && e.target.dataset.value; |
| 57 | + insertOpeningParenthesis(buttonValue); |
| 58 | + insertClosingParenthesis(buttonValue); |
| 59 | + deleteEverythingFromScreen(buttonValue); |
| 60 | + toggleSign(buttonValue); |
| 61 | + canUserAddDot(buttonValue); |
| 62 | + userClicksOnEqualButton(buttonValue); |
| 63 | + handlingZeroFollowedByAdecimal(buttonValue); |
| 64 | + removesDecimalPointIfPrecededByAnOperator(buttonValue); |
| 65 | + handleNumberButton(buttonValue); |
| 66 | + deteLastEntry(buttonValue); |
| 67 | + convertToPercentage(buttonValue); |
| 68 | + }); |
| 69 | + }); |
| 70 | + // forEach ends & functions creations begins |
| 71 | + function convertToPercentage(button) { |
| 72 | + if (button === "%") { |
| 73 | + currentExpression = Number(data.join("")); |
| 74 | + currentExpression = currentExpression / 100; |
| 75 | + data = [currentExpression]; |
| 76 | + console.log(data); |
| 77 | + screenElement.innerText = String(currentExpression); |
| 78 | + } |
| 79 | + } |
| 80 | + function deteLastEntry(button) { |
| 81 | + if (button === "DE") { |
| 82 | + let newArray = data.slice(ZERO, -1); |
| 83 | + screenElement.innerText = newArray.join(""); |
| 84 | + data = newArray; |
| 85 | + if (screenElement.innerText === "") { |
| 86 | + screenElement.innerText = String(ZERO); |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | + function canUserAddDot(button) { |
| 91 | + if (button === ".") { |
| 92 | + var dotAllowed = true; |
| 93 | + for (var i = data.length - 1; i >= ZERO; i--) { |
| 94 | + if (data[i] === ".") { |
| 95 | + dotAllowed = false; |
| 96 | + break; |
| 97 | + } |
| 98 | + else if (operatorRegex.test(String(data[i]))) { |
| 99 | + break; |
| 100 | + } |
| 101 | + } |
| 102 | + if (dotAllowed) { |
| 103 | + if (data.length == ZERO) { |
| 104 | + data.push("0"); |
| 105 | + } |
| 106 | + else if (operatorRegex.test(String(data[data.length - 1]))) { |
| 107 | + data.push("0"); |
| 108 | + } |
| 109 | + data.push("."); |
| 110 | + } |
| 111 | + screenElement.innerText = data.join(""); |
| 112 | + } |
| 113 | + } |
| 114 | + function deleteEverythingFromScreen(button) { |
| 115 | + if (button === "AC") { |
| 116 | + screenElement.innerText = ""; |
| 117 | + data = []; |
| 118 | + screenElement.innerText = String(ZERO); |
| 119 | + } |
| 120 | + } |
| 121 | + // function toggleSign(button) { |
| 122 | + // if (button === "minus") { |
| 123 | + // console.log(data[0]) |
| 124 | + // currentExpression = data.join(""); |
| 125 | + // console.log(currentExpression) |
| 126 | + // let reversedExpression = currentExpression.split("").join(""); |
| 127 | + // console.log(reversedExpression) |
| 128 | + // let match = reversedExpression.match(/(\d+(\.\d+)?)|(\D+)/); // Match a number or non-digit |
| 129 | + // if (match) { |
| 130 | + // let start = currentExpression.length - match[ZERO].length; |
| 131 | + // let end = currentExpression.length; |
| 132 | + // let currentValue = Number(match[ZERO]); |
| 133 | + // if (!isNaN(currentValue)) { |
| 134 | + // currentValue = -currentValue; |
| 135 | + // data = data |
| 136 | + // .slice(ZERO, start) |
| 137 | + // .concat(currentValue.toString().split(""), data.slice(end)); |
| 138 | + // screenElement.innerText = data.join(""); |
| 139 | + // } |
| 140 | + // } |
| 141 | + // } |
| 142 | + // } |
| 143 | + // The unshift() method of Array instances adds the specified elements to the beginning |
| 144 | + // of an array and returns the new length of the array. |
| 145 | + // The shift() method of Array instances removes the first element from an array and returns |
| 146 | + // that removed element. This method changes the length of the array. |
| 147 | + minus.addEventListener("click", toggleSign); |
| 148 | + // function toggleSign(button) { |
| 149 | + // let value = Number(data.join("")) |
| 150 | + // if (button === "minus") { |
| 151 | + // if (value > 0) { |
| 152 | + // value = -value |
| 153 | + // console.log(value); |
| 154 | + // screenElement.innerText = value; |
| 155 | + // } if (value < 0) { |
| 156 | + // console.log("smaller than zero") |
| 157 | + // value = value * -1 |
| 158 | + // console.log(value) |
| 159 | + // screenElement.innerText = value; |
| 160 | + // } |
| 161 | + // // screenElement.innerText = value; |
| 162 | + // data = [value] |
| 163 | + // } |
| 164 | + // } |
| 165 | + function toggleSign(button) { |
| 166 | + let value = Number(data.join("")); |
| 167 | + if (button === "minus") { |
| 168 | + if (value > 0) { |
| 169 | + value = -value; |
| 170 | + } |
| 171 | + else if (value < 0) { |
| 172 | + value = value * -1; |
| 173 | + } |
| 174 | + screenElement.innerText = String(value); |
| 175 | + data = [value]; |
| 176 | + } |
| 177 | + } |
| 178 | + function insertOpeningParenthesis(button) { |
| 179 | + if (button === "(") { |
| 180 | + let isOpenparenthesis = true; |
| 181 | + for (let i = data.length - 1; i >= ZERO; i--) { |
| 182 | + if (/^\d$/.test(String(data[i]))) { |
| 183 | + isOpenparenthesis = false; |
| 184 | + break; |
| 185 | + } |
| 186 | + if (data[i] === ")") { |
| 187 | + isOpenparenthesis = false; |
| 188 | + break; |
| 189 | + } |
| 190 | + if (operatorRegex.test(String(data[i]))) { |
| 191 | + break; |
| 192 | + } |
| 193 | + } |
| 194 | + if (isOpenparenthesis) { |
| 195 | + data.push("("); |
| 196 | + } |
| 197 | + screenElement.innerText = data.join(""); |
| 198 | + } |
| 199 | + } |
| 200 | + function insertClosingParenthesis(button) { |
| 201 | + if (button === ")") { |
| 202 | + data.push(")"); |
| 203 | + screenElement.innerText = data.join(""); |
| 204 | + } |
| 205 | + } |
| 206 | + function handlingZeroFollowedByAdecimal(button) { |
| 207 | + if (Number(button) === ZERO && screenElement.innerText.startsWith(ZERO_DOT)) { |
| 208 | + screenElement.innerText += button; |
| 209 | + } |
| 210 | + } |
| 211 | + function removesDecimalPointIfPrecededByAnOperator(button) { |
| 212 | + if (operatorRegex.test(button)) { |
| 213 | + if (data.slice(-1)[ZERO] === ".") { |
| 214 | + data.pop(); |
| 215 | + } |
| 216 | + button === "*" ? (button = "x") : button === "/" ? (button = "÷") : button; |
| 217 | + data.push(button); |
| 218 | + screenElement.innerText = data.join(""); |
| 219 | + } |
| 220 | + } |
| 221 | + function handleNumberButton(button) { |
| 222 | + if (!isNaN(Number(button))) { |
| 223 | + screenElement.innerText = button; |
| 224 | + data.push(screenElement.innerText); |
| 225 | + screenElement.innerText = data.join(""); |
| 226 | + } |
| 227 | + } |
| 228 | + function userClicksOnEqualButton(button) { |
| 229 | + if (button === "=") { |
| 230 | + try { |
| 231 | + const replacedArray = data.map((item) => item === "x" ? "*" : item === "÷" ? "/" : item); |
| 232 | + if (areYouDividingdZeroByZero(replacedArray)) { |
| 233 | + screenElement.innerText = "0÷0 is an invalid format. Press AC"; |
| 234 | + } |
| 235 | + else { |
| 236 | + let result = eval(replacedArray.join("")); |
| 237 | + const history = getHistoryFromLocalStorage(); |
| 238 | + history.push([...replacedArray, "=", result].join("").split(",")); // Used slice() at first. But slice() is not sufficient because it only creates a shallow copy of the array, and modifications to the new array will still affect the original array. The spread syntax ([...replacedArray]), which creates a shallow copy as well, is a concise way to create a new array with the same elements as the existing array. While ensuring that modifications to historyEntries do not affect replacedArray, and vice versa |
| 239 | + replacedArray.splice(replacedArray.length, 0, "=", result); |
| 240 | + displayResult(replacedArray, result); |
| 241 | + screenElement.innerText = !Number.isFinite(result) |
| 242 | + ? "You cannot divide by zero. Press AC" |
| 243 | + : result; |
| 244 | + data = []; |
| 245 | + data.push(result); |
| 246 | + setHistoryToLocalStorage(history); |
| 247 | + createHistoryList(history, historyElement); |
| 248 | + togglesClearHistoryButton(historyElement); |
| 249 | + } |
| 250 | + } |
| 251 | + catch (e) { |
| 252 | + console.error(e); |
| 253 | + screenElement.innerText = `${e.name} press AC`; |
| 254 | + } |
| 255 | + } |
| 256 | + } |
| 257 | + function areYouDivindingByZero(array) { |
| 258 | + for (let i = ZERO; i < array.length - 2; i++) { |
| 259 | + if (!isNaN(Number(array[i])) && |
| 260 | + array[i + 1] === "/" && |
| 261 | + array[i + 2] === "0") { |
| 262 | + return true; |
| 263 | + } |
| 264 | + } |
| 265 | + return false; |
| 266 | + } |
| 267 | + function areYouDividingdZeroByZero(array) { |
| 268 | + for (let i = ZERO; i < array.length - 2; i++) { |
| 269 | + if (array[i] === "0" && array[i + 1] === "/" && array[i + 2] === "0") { |
| 270 | + return true; |
| 271 | + } |
| 272 | + } |
| 273 | + return false; |
| 274 | + } |
| 275 | + function displayResult(array, outcome) { |
| 276 | + array = []; |
| 277 | + array.push(outcome); |
| 278 | + } |
| 279 | + function createHistoryList(entries, element) { |
| 280 | + element.innerHTML = ""; |
| 281 | + entries |
| 282 | + .slice(-10) |
| 283 | + .reverse() |
| 284 | + .forEach((entry) => { |
| 285 | + const listItem = document.createElement("li"); |
| 286 | + listItem.textContent = entry; |
| 287 | + element.appendChild(listItem); |
| 288 | + }); |
| 289 | + } |
| 290 | + function getHistoryFromLocalStorage() { |
| 291 | + return JSON.parse(localStorage.getItem("calculatorHistory") || "[]"); |
| 292 | + } |
| 293 | + function setHistoryToLocalStorage(history) { |
| 294 | + localStorage.setItem("calculatorHistory", JSON.stringify(history.slice(-10))); |
| 295 | + } |
| 296 | + clearHistoryBtn.addEventListener("click", () => { |
| 297 | + historyElement.innerHTML = ""; |
| 298 | + clearHistoryInLocalStorage(); |
| 299 | + togglesClearHistoryButton(historyElement); |
| 300 | + }); |
| 301 | + function clearHistoryInLocalStorage() { |
| 302 | + localStorage.removeItem("calculatorHistory"); |
| 303 | + } |
| 304 | + function togglesClearHistoryButton(element) { |
| 305 | + clearHistoryBtn.classList.toggle("display", element.childElementCount > 0); |
| 306 | + } |
| 307 | + // functions creations ends |
| 308 | +}); |
0 commit comments