Compare commits

...

2 Commits

Author SHA1 Message Date
CPPAlien
beb630d5a2 fix: calc bug 2021-06-22 16:59:52 +08:00
CPPAlien
eeb4f8a0fa fix: 四则运算 2021-06-22 16:45:39 +08:00
2 changed files with 52 additions and 46 deletions

View File

@ -1,48 +1,54 @@
module.exports = function (s) { /* eslint-disable */
s = s.trim(); // 四则运算
const stack = new Array();
let preSign = '+'; !(function () {
let numStr = ''; var calculate = function (s) {
const n = s.length; s = s.trim();
for (let i = 0; i < n; ++i) { const stack = new Array();
if (s[i] === '.' || (!isNaN(Number(s[i])) && s[i] !== ' ')) { let preSign = '+';
numStr += s[i]; let numStr = '';
} else if (s[i] === '(') { const n = s.length;
let isClose = 1; for (let i = 0; i < n; ++i) {
let j = i; if (s[i] === '.' || (!isNaN(Number(s[i])) && s[i] !== ' ')) {
while (isClose > 0) { numStr += s[i];
j += 1; } else if (s[i] === '(') {
if (s[j] === '(') isClose += 1; let isClose = 1;
if (s[j] === ')') isClose -= 1; let j = i;
while (isClose > 0) {
j += 1;
if (s[j] === '(') isClose += 1;
if (s[j] === ')') isClose -= 1;
}
numStr = `${calculate(s.slice(i + 1, j))}`;
i = j;
} }
numStr = `${calculate(s.slice(i + 1, j))}`; if ((isNaN(Number(s[i])) && s[i] !== '.') || i === n - 1) {
i = j; let num = parseFloat(numStr);
} switch (preSign) {
if (isNaN(Number(s[i]) && s[i] !== '.') || i === n - 1) { case '+':
let num = parseFloat(numStr); stack.push(num);
switch (preSign) { break;
case '+': case '-':
stack.push(num); stack.push(-num);
break; break;
case '-': case '*':
stack.push(-num); stack.push(stack.pop() * num);
break; break;
case '*': case '/':
stack.push(stack.pop() * num); stack.push(stack.pop() / num);
break; break;
case '/': default:
stack.push(stack.pop() / num); break;
break; }
default: preSign = s[i];
break; numStr = '';
} }
preSign = s[i];
numStr = '';
} }
} let ans = 0;
let ans = 0; while (stack.length) {
while (stack.length) { ans += stack.pop();
ans += stack.pop(); }
} return ans;
return ans; };
}; module.exports = calculate;
})();

View File

@ -851,7 +851,7 @@ function setStringPrototype(screenK, scale) {
const formula = /^calc\((.+)\)$/.exec(this); const formula = /^calc\((.+)\)$/.exec(this);
if (formula && formula[1]) { if (formula && formula[1]) {
// 进行 calc 计算 // 进行 calc 计算
const afterOne = formula[1].replace(/([^\s]+)\.(left|right|bottom|top|width|height)/g, word => { const afterOne = formula[1].replace(/([^\s\(\+\-\*\/]+)\.(left|right|bottom|top|width|height)/g, word => {
const [id, attr] = word.split('.'); const [id, attr] = word.split('.');
return penCache.viewRect[id][attr]; return penCache.viewRect[id][attr];
}); });