2 回答
TA贡献1719条经验 获得超6个赞
对我来说一切似乎都很好,只需根据给定的规范清理输入方程,所有测试用例都将得到满足。
对handleEqualClick()功能进行以下更改:
handleEqualsClick = () => {
const { input } = this.state;
//todo ? if the last char is oper, delete it
// console.log(input);
let eq = [];
for (let ch of [...input]) {
if (!eq.length) {
eq.push(ch);
} else {
if (ch === "-") {
eq.push("-");
} else if ("+-*/".includes(ch) && "+-*/".includes(eq[eq.length - 1])) {
while ("+-*/".includes(ch) && "+-*/".includes(eq[eq.length - 1])) {
eq.pop();
}
eq.push(ch);
} else {
eq.push(ch);
}
}
}
let sanitizedInput = eq.join("");
console.log(sanitizedInput);
let result = +eval(sanitizedInput).toFixed(7).toString();
console.log("result:", result);
if (result.length > 11) {
result = result.slice(0, 11);
}
this.setState((state) => ({
showInput: false,
output: result,
input: result //test14
}));
};
TA贡献1946条经验 获得超3个赞
一些说明:我想要 1) 通过测试#13,2) 在显示上看到正确的字符
功能上有错误fixInput
,我this.state.input
在需要更新版本时进行了测试,该版本是this.state.input + value
.
function fixInput(inputStr, currentOp) {
const lastTwoOp = /([+\-*/]{2})$/;
const lastThreeOp = /([+\-*/]{3})$/;
const allowTwo = /(\*|\/)-/;
const toTest = inputStr + currentOp; //<=
if (lastTwoOp.test(toTest) && !allowTwo.test(toTest)) {
inputStr = inputStr.slice(0, -1) + currentOp;
} else if (lastThreeOp.test(toTest)) {
inputStr = inputStr.slice(0, -2) + currentOp;
} else {
inputStr += currentOp;
}
return inputStr;
}
添加回答
举报