This was the task (I don't know the exact wordings anymore):
You get a string with operation as input:
- if it is a number push it to stack
- if it is "DUP", then duplicate the one one top and push it to the
stack
- if it is "POP" then remove the one on top
- if it is "+" add the two numbers on top of the stack and replace
both with the result of the addition
- if it is "-" then minus the two numbers on top (the second minus
the first) of the stack and replace both with the result of the
subtraction
- if an error occurs, e.g. not enough numbers to add/subtract/pop,
then return -1
Examples:
Input: "3 DUP 5 - -"
Output: -1
Input: "13 DUP 4 POP 5 DUP + DUP + -"
Output: 7
Input: "5 6 + -"
Output: -1
My solution:
function solution(S) {
if (!S.length) {
return -1;
}
const stack = new Array();
const push = n => stack.push(Number(n));
const pop = () => {
if (!stack.length) {
throw new Error('empty');
}
return stack.pop();
}
const duplicate = () => {
try {
const dup = pop();
push(dup);
push(dup);
} catch(e) {
throw new Error(e);
}
};
const add = () => {
try {
const sum1 = pop();
const sum2 = pop();
push(sum1 + sum2);
} catch(e) {
throw new Error(e);
}
};
const minus = () => {
try {
const min1 = pop();
const min2 = pop();
push(min1 - min2);
} catch(e) {
throw new Error(e);
}
};
const ops = {
"DUP": duplicate,
"POP": pop,
"+": add,
"-": minus,
};
const input = S.split(' ');
input.forEach(x => {
if (!isNaN(x)) {
push(x);
} else {
try {
const sanitzedX = x.toUpperCase();
if (!ops[sanitzedX]) {
return -1;
}
ops[sanitzedX]();
} catch(e) {
return -1;
}
}
});
try {
return pop();
} catch(e) {
return -1;
}
}
console.log(solution("3 DUP 5 - -"));
console.log(solution("13 DUP 4 POP 5 DUP + DUP + -"));
console.log(solution("5 6 + -"));