This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
124. calculate arithmetic expression
One possible solution is:
/** * @param {string} str * @return {number} */function calculate(str) { const tokens = tokenize(str); function parseExpr() { let left = parseTerm(); while (tokens.length > 0 && (tokens[0] === '+' || tokens[0] === '-')) { const op = tokens.shift(); const right = parseTerm(); if (op === '+') { left += right; } else { left -= right; } } return left; } function parseTerm() { let left = parseFactor(); while (tokens.length > 0 && (tokens[0] === '*' || tokens[0] === '/')) { const op = tokens.shift(); const right = parseFactor(); if (op === '*') { left *= right; } else { left /= right; } } return left; } function parseFactor() { if (tokens[0] === '(') { tokens.shift(); // consume '(' const value = parseExpr(); tokens.shift(); // consume ')' return value; } else { return Number(tokens.shift()); } } // start parsing from the expression level return parseExpr();}
The calculate
function first tokenizes the input string using the tokenize
function from the previous question. Then it defines three helper functions: parseExpr
for parsing addition and subtraction expressions, parseTerm
for parsing multiplication and division expressions, and parseFactor
for parsing numbers and parentheses.
Each function uses a recursive descent parsing technique, meaning that it calls other functions to parse sub-expressions when needed. The parsing order is determined by operator precedence and associativity rules, which are encoded in the function structure.
The result of the calculate
function is the value of the top-level expression, which is obtained by calling parseExpr
.