98 lines
No EOL
2.6 KiB
JavaScript
98 lines
No EOL
2.6 KiB
JavaScript
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;
|
|
}
|
|
}
|
|
} |