Add js code

This commit is contained in:
Nyymix 2022-05-03 13:49:39 +03:00
parent 98324d1b2d
commit e331b98e84
2 changed files with 133 additions and 0 deletions

98
calculator.js Normal file
View file

@ -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
View file

@ -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;
}