Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function main(allInstructions) {
- const AvailableOperations = {
- ['+']: (a, b) => a + b,
- ['-']: (a, b) => a - b,
- ['*']: (a, b) => a * b,
- ['/']: (a, b) => a / b,
- }
- const stack = [];
- for (const instruction of allInstructions) {
- const number = Number(instruction);
- if (isNumber(number)) {
- stack.push(number);
- } else {
- if (notEnoughNumbersInStack(stack)) {
- console.log('Error: not enough operands!');
- return; // potential bug
- }
- const rightOperand = stack.pop();
- const leftOperand = stack.pop();
- const currentOperation = AvailableOperations[instruction];
- const result = currentOperation(leftOperand, rightOperand);
- stack.push(result);
- }
- }
- if (stack.length === 1) {
- console.log(stack.pop());
- } else {
- console.log('Error: too many operands!');
- }
- function isNumber(potentialNumber) {
- return !isNaN(potentialNumber);
- }
- function notEnoughNumbersInStack(stack) {
- return stack.length < 2;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement