I'm in the proccess of creating 'Windows-like' calculator. I already built my calculator in html and set input to read-only to resemble that of Windows'. Now, I know you can control basic input by creating proper regex, but is it the case with read-only?
What I want is that I control what goes in input box by adding event listeners than updating input if conditions are met which I already did but can I restrict my code further by using regex or some other technique for proper math algorithms like 3.55*(4/(1+1)) ? I hope I'm clear about what I need.
I tried setting countless variables and control them with if/switch statements which worked in the end, but it took me around 100 lines of code which quickly became a nightmare to control, so I started from scratch and looking for alternatives, and if what I learned about JS is true, it's possible. Only pure JS and no other libraries, please. Here's my current JS code:
const domRef = {
inputMain: document.getElementById('input-main'),
inputSecondary: document.getElementById('input-secondary'),
buttons: document.getElementById('calculator-basic').querySelectorAll('button')
}
function handleClick(event) {
let target = event.target;
if (target.classList.contains('expressions')) { // operands and operators
let input = target.textContent;
updateInputMain(input);
}
}
function handleKeypress(event) {
let target;
for (let i = 0; i < domRef.buttons.length; i++) {
if (domRef.buttons[i].textContent === event.key) {
target = domRef.buttons[i];
target.click();
}
}
}
function updateInputMain(input) {
domRef.inputMain.value += input;
}
for (let i = 0; i < domRef.buttons.length; i++) {
domRef.buttons[i].addEventListener('click', handleClick);
}
document.body.addEventListener('keypress', handleKeypress);
I would suggest using a specialized library, eg Math.js
Doing powerful calculations become as easy as that:
math.sqrt(-4); // 2i console.log(math.eval(3.55*(4/(1+1))));
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/4.4.2/math.min.js"></script>
Math.js contains a function math.parse to parse expressions into an expression tree. That should come handy.
Also, we can wrap parse or eval with a try-catch block to check for syntax errors:
try { math.parse('3.55*(4/(1+1)'); } catch(error) { console.error(error); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/4.4.2/math.min.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.