第 10 期 | Phase A: 计算引擎的并行开发
💡 进群学习加 wx: agentupdate
(申请发送: agentupdate)
(申请发送: agentupdate)
app.js(由 logic-dev 创建)— Shunting-yard 计算引擎
// 运算符优先级
const PRECEDENCE = {
'+': 1, '-': 1,
'×': 2, '*': 2, '÷': 2, '/': 2,
'%': 3, 'unary-': 4
};
// 词法分析
function tokenize(expression) {
// "1+2*3" → ['1', '+', '2', '*', '3']
}
// Shunting-yard 算法 → RPN
function parseExpression(tokens) {
// ['1', '+', '2', '*', '3'] → ['1', '2', '3', '*', '+']
}
// RPN 求值
function evaluate(rpn) {
// 栈式求值,除零返回 "Error"
}
// 实时预览(不完整表达式不计算)
function previewResult(expression) {
// 括号不匹配 → 返回 ''
// 末尾是运算符 → 返回 ''
}
// 输入辅助(纯函数,不依赖 DOM)
function appendNumber(current, digit) { /* ... */ }
function appendOperator(current, op) { /* ... */ }
function appendDecimal(current) { /* ... */ }
function toggleSign(current) { /* ... */ }
// DOM 绑定层(与纯函数分离)
function initCalculator() {
initElements();
loadModePreference();
bindButtonEvents();
bindKeyboardEvents();
bindModeToggle();
updateDisplay();
}
// 导出(Node.js 测试兼容)
if (typeof module !== 'undefined' && module.exports) {
module.exports = { tokenize, parseExpression, evaluate, /* ... */ };
}
架构关键:纯函数与 DOM 分离
┌─────────────────────────────────┐
│ 纯函数层(不依赖 DOM) │
│ tokenize → parseExpression → evaluate │
│ appendNumber, appendOperator, ... │
│ ✅ 可独立测试(Node.js) │
└──────────────┬──────────────────┘
│
┌──────────────▼──────────────────┐
│ DOM 交互层 │
│ initCalculator, handleButtonClick │
│ bindKeyboardEvents, toggleMode │
│ ⚠️ 需浏览器环境测试 │
└─────────────────────────────────┘