-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
93 lines (75 loc) · 2.08 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { INPUT_REQUIREMENTS_MESSAGE, OPERATIONS, WELCOME_MESSAGE } from './constants.js';
import { isNumber, isOperator } from './helpers.js';
import { createInterface } from 'readline';
const rl = createInterface({
input: process.stdin,
output: process.stdout
});
process.on('exit', () => {
rl.close();
console.log('Bye!!!');
});
const operands = [];
const addOperand = (value) => {
operands.push(+value);
}
const calculate = (operator) => {
const operation = OPERATIONS[operator];
if (operands.length > 1) {
const secondOperand = operands.pop();
const firstOperand = operands.pop();
const result = operation(firstOperand, secondOperand);
addOperand(result);
}
}
const clear = () => {
console.log(`Values cleared successfully! ${INPUT_REQUIREMENTS_MESSAGE}`);
operands.length = 0;
}
const getCurrentValue = () => {
const value = operands[operands.length - 1];
if (!value && value !== 0 ) return '';
return Number.isInteger(value) ? value.toFixed(1) : value;
};
const handleInput = (input) => {
switch(input) {
case 'q':
case 'quit':
process.exit();
break;
case 'c':
case 'clear':
clear();
break;
default:
handleValues(input);
break;
}
}
const handleValues = (inputString) => {
const inputValues = inputString.replace( /\s\s+/g, ' ' ).split(' ');
const hasCorrectInput = inputValues.every(value => isNumber(value) || isOperator(value));
if (!hasCorrectInput) {
console.log(`Incorrect input. ${INPUT_REQUIREMENTS_MESSAGE}`);
} else {
inputValues.forEach(value => {
if(isNumber(value)) {
addOperand(value);
} else {
calculate(value);
}
});
}
}
const listenToInput = () => {
rl.question("> ", function(input) {
handleInput(input);
console.log(getCurrentValue());
listenToInput();
});
}
const run = () => {
console.log(WELCOME_MESSAGE);
listenToInput();
}
run();