Four operations, first multiplication and division, then addition and subtraction 0 to 9, +-*/, no parentheses
1. Algorithm idea
The low-priority operator encounters the high-priority operator to its right, the right-priority operator encounters the same priority operator, and the left-priority operator encounters the low-priority operator to its right, and the left-priority operator encounters the first-priority operator to its left
2. The data structure adopts the stack structure
3. Unit testing
Let x = '+ 3 + 2 * 3 + orange-red + 6/2 9/3 + 5 * 3-8' / / OPERATOR precedence 0 ~ 1 let OPERATOR = [[' + ', 0], [' - ', 0], [' * ', 1], ['/', 1]] function run (x) {let nArr = [] let oArr = [] let iRet = "let I = 0" // Header pointer let sNToken = x.charcodeat (I) -48 let sPToken = '' let nPriority = 0 if (sNToken < 0 || sNToken > 9) { iRet = `Error at position ${i} : is not a number(${x.charAt(i)})! ` } else { nArr.push(sNToken) i = 1 for (; i < x.length - 1 ;) {// get operator sPToken = x.charat (I); NPriority = validateOperator(sPToken) if (typeof nPriority! == 'number') {iRet = 'nPriority at position ${I}' break} // Obtain the second sNToken = x.charcodeat (I + 1) -48 if (sNToken < 0) || sNToken > 9) { iRet = `Error at position ${i + 1} : is not a number(${x.charAt(i + 1)})! Typeof (iRet = stackOut(oArr, nArr, false, nPriority)) == 'string')? true : iRet = ''; If (iRet) {break} narr. push(sNToken) let opPair = [] opPair[0] = sPToken opPair[1] = nPriority oarr. push(opPair) i += 2 } (typeof(iRet = stackOut(oArr, nArr, true)) == 'string')? true:iRet=''; } if (iRet) { console.log(iRet) } else { nRet = nArr.pop() } return nRet } function stackOut (oArr, nArr, BIsNotCareAboutPriority, nPriority) {let iRet = "// whether the priority of the top element in the operator stack is greater than the current priority //let flag = oarr.length! = 0 && (bIsNotCareAboutPriority || oArr[oArr.length - 1][1] >= nPriority) while (oArr.length ! = 0 && (bIsNotCareAboutPriority | | oArr [oArr. Length - 1] [1] > = nPriority)) {/ / flare stack calculation let n let n2 = nArr. Pop () let n1 = nArr.pop() let op = oArr.pop()[0] n = calculate(op, n1, n2) if (typeof n ! == 'number') { iRet = n; } else { nArr.push(n) } } return iRet === '' ? true : iRet } function calculate (op, n1, n2) { let n; let iRet = '' switch (op) { case '+': n = n1 + n2; break; case '-': n = n1 - n2; break; case '*': n = n1 * n2; break; case '/': n = n1 / n2; break; default: iRet = `Error in calculate ${op}` console.log(iRet) break } if (iRet ! = = '&& (! isFinite(n) || isNaN(n))) { iRet = 'Error, the result is invalid' } return iRet === '' ? n : iRet } function validateOperator (sPToken) { let iRet = '' let j = 0 for (j = 0; j < OPERATOR.length; j++) { if (OPERATOR[j][0] == sPToken) { break } } if (j >= OPERATOR.length) { iRet = `Error: Syntax error: invalid operator "${sPToken}"` } return iRet === '' ? OPERATOR[j][1] : iRet } console.log(run(x))Copy the code