Javascript 我在基于字符串参数修改堆栈时遇到了这个面试问题

Javascript 我在基于字符串参数修改堆栈时遇到了这个面试问题,javascript,stack,Javascript,Stack,我不再有他们给我的挑战问题的确切措辞,因为我提交了它,我再也无法访问它了。然而,我确实用自己的话写下了提示。我得到了66%的回报,他们希望更高的回报。如果有人能给我一个好主意,这样我就可以改进了,我不确定我在这里没有碰到什么边缘案例 -Write a function that takes a string S as an argument and depending on each 'word' in the string mutate a STACK and at the end retur

我不再有他们给我的挑战问题的确切措辞,因为我提交了它,我再也无法访问它了。然而,我确实用自己的话写下了提示。我得到了66%的回报,他们希望更高的回报。如果有人能给我一个好主意,这样我就可以改进了,我不确定我在这里没有碰到什么边缘案例

-Write a function that takes a string S as an argument and depending on each 'word' in the string mutate a STACK and at the end return the top most element the of STACK. 

--- Each 'word' in the string is separated by a space and will always either be an INTEGER (from 0 to 2^20-1) , 'DUP', 'POP', '-', or '+'
    --- EX: '2 34 - DUP +'

--- If the 'word' is an INTEGER PUSH IT ON TOP OF THE STACK.
--- If the 'word' is 'DUP', DUPLICATE THE TOPMOST EL ON THE STACK AND PUSH IT ONTO THE STACK.
--- If the 'word' is 'POP', POP THE TOPMOST EL OFF THE STACK.
--- If the 'word' is '-', POP THE TOP TWO ELs OFF THE STACK, SUBTRACT THE SECOND FROM THE FIRST (TOPMOST) AND PUSH THE RESULTING DIFFERENCE ONTO THE STACK.
--- If the 'word' is '+', POP THE TOP TWO ELs OFF THE STACK, ADD THE VALUES TOGETHER AND PUSH THE SUM ONTO THE STACK.

*** ERROR HANDLING: ALL ERRORS RETURN -1
        - If there are insufficient ELs on the stack to perform an action return and error. ie. stack.length < 2 && action is '-'||'+'
        - If the result of '-' action is a negative integer return an error.
        - If at the end of the function the stack's length is < 1 return an error.
-编写一个函数,该函数将字符串S作为参数,并根据字符串中的每个“字”对堆栈进行变异,最后返回堆栈的最顶层元素。
---字符串中的每个“字”都用空格分隔,并且总是一个整数(从0到2^20-1)、“DUP”、“POP”、““-”或“+”
---例如:“2 34-DUP+”
---如果“word”是整数,则将其推到堆栈顶部。
---如果“word”是“DUP”,复制堆栈上最顶部的EL并将其推到堆栈上。
---如果“单词”是“POP”,则从堆栈中弹出最顶部的EL。
---如果“单词”为“-”,则将堆栈顶部的两个EL弹出,从第一个(最顶部)减去第二个EL,并将结果差异推送到堆栈上。
---如果“word”是“+”,则从堆栈中弹出顶部的两个EL,将值相加,并将总和推送到堆栈中。
***错误处理:所有错误返回-1
-如果堆栈上没有足够的EL来执行操作,则返回并出错。即stack.length<2&&action为“-”| |“+”
-如果“-”操作的结果是负整数,则返回错误。
-如果在函数末尾,堆栈长度小于1,则返回错误。

const stackString=S=>{
//声明堆栈
让堆栈=[];
//按空格将字符串拆分为数组
常量数组=S.split(“”);
//循环通过阵列,对每个el的堆栈执行适当的操作
for(设i=0;i=2){
const[first,second]=[parseInt(stack.pop()),parseInt(stack.pop())];
常数和=第一个+第二个;
叠加推(和);
}
//“-”案例
if(数组[i]=='-'&&stack.length>=2){
常量[first,second]=[stack.pop(),stack.pop()];
常数差=第一秒;
叠加推(差分);
//负整数的错误案例
如果(差异<0)返回-1;
}
}
//空的结束堆栈情况
if(stack.length==0){
返回-1;
}else返回堆栈[stack.length-1];
};
//测试:
console.log(stackString('123445'));//=>45
log(stackString('2dup+46-');//=>2.
log(stackString('2dup+46pop');//=>4.
console.log(stackString('2pop'));//空堆栈错误==>-1
console.log(stackString('32-');//负整数错误==>-1
console.log(stackString('45-');//堆栈长度错误'-'=>-1
console.log(stackString('45+');//堆栈长度错误“+”=>-1