Browse Source

Add js code

master
Nyymix 2 months ago
parent
commit
e331b98e84
  1. 98
      calculator.js
  2. 35
      main.js

98
calculator.js

@ -0,0 +1,98 @@
class Calculator {
constructor() {
this.curr = '';
this.prew = '';
this.operator = '';
}
clear() {
this.curr = '';
this.prew = '';
this.operator = '';
}
delete() {
this.curr = this.curr.slice(0, -1)
}
append(val) {
if (val === '0' && this.curr === '0') {
this.curr = this.curr;
} else {
this.curr = this.curr + val;
}
}
_calculate(prew, curr, operator) {
switch (operator) {
case 'ADD':
return +prew + +curr;
case 'SUB':
return +prew - +curr;
case 'MUL':
return +prew * +curr;
case 'DIV':
return +prew / +curr;
default:
console.log('Invalid operator');
break;
}
}
pressbutton(button) {
switch (button) {
case 'ACC':
this.clear();
break;
case 'DEL':
this.delete();
break;
case 'ADD':
case 'SUB':
case 'MUL':
case 'DIV':
if (this.curr === '' && this.prew !== '') {
this.operator = button;
break;
}
if (this.curr !== '' && this.prew !== '') {
this.prew = this._calculate(this.prew, this.curr, this.operator);
this.curr = '';
this.operator = '';
} else {
if (this.curr === '' && this.prew === '') {
this.curr = '0';
}
this.prew = this.curr;
this.curr = '';
}
this.operator = button;
break;
case 'EQU':
if (this.curr !== '' && this.prew !== '') {
this.curr = this._calculate(this.prew, this.curr, this.operator);
this.prew = '';
this.operator = '';
}
break;
case 'DOT':
if (this.curr.includes('.')) {
break;
}
if (this.curr === '') {
this.curr = '0';
}
this.append('.')
break;
case 'NEG':
if (this.curr === '') {
this.curr = '-';
}
break;
default:
this.append(button)
break;
}
}
}

35
main.js

@ -1 +1,36 @@
const dis_big = document.getElementById("dis_big");
const dis_sml = document.getElementById("dis_sml");
const calc = new Calculator();
const buttons = document.querySelector('.buttons');
buttons.addEventListener('click', e => {
const value = e.target.value;
PressButton(value);
})
function PressButton(button) {
calc.pressbutton(button);
tmp = '';
switch (calc.operator) {
case 'ADD':
tmp = ' +';
break;
case 'SUB':
tmp = ' -';
break;
case 'MUL':
tmp = ' *';
break;
case 'DIV':
tmp = ' /';
break;
default:
console.log('Invalid operator');
break;
}
dis_big.innerText = calc.curr;
dis_sml.innerText = calc.prew + tmp;
}
Loading…
Cancel
Save