每日一练

102 阅读1分钟

题目:写一个函数,计算 1+2*(3+4*(5+6))

//分割字符串为数组,将数字有运算符分开const _splitNumber = res => { return res.match(/\d+|[^\d\s\t]/g) }// 判断元素是否为数组const _isNumber = res => { return (/^\d+$/).test(res) }// 判断是否为 + - * / 运算符const _isOperator = res => { return (/^[\+\-\*\/#]$/).test(res) }// 判断运算符的级别const _isSymbol = createIsSymbol()// 进行运算const _operator = {   '+': (first, last) => { return first + last },   '-': (first, last) => { return first - last },   '*': (first, last) => { return first * last },   '/': (first, last) => { return first / last },}// 计算式子的函数 ---- 采用波兰式function math(number) {   let num = _splitNumber(number)   return operator(transformation(num));}function transformation(number) {   number.push('#')   let num = []   let operator = []   number.forEach(item => {       if (_isNumber(item)) {           // item 为 数字           num.push(item);       } else if (_isOperator(item)) {           // item 为 运算符           while (operator.length) {               const op = operator[operator.length - 1]               if (op === "(") {                   // 上次存入的运算符为 (                   break;               } else if (_isSymbol(item) > _isSymbol(op)) {                   // 当前的运算符优先级大于上次存储的那个                   break;               } else {                   num.push(operator.pop())               }           }           operator.push(item)      } else {           // item( )           if (item === '(') {               // 当前符号为 (               operator.push(item)           } else {               // 当前符号为 )               while (operator[operator.length - 1] !== '(') {                   num.push(operator.pop())               }               operator.pop()           }      }   });   return num;}function operator(number) {    let calcStack = [];    number.forEach(item => {        if (_isNumber(item)) {            calcStack.push(+item)        } else {            const firstNumber = calcStack.pop();            const lastNumber = calcStack.pop();            calcStack.push(_operator[item](firstNumber, lastNumber))        }    })    return calcStack[0];}function createIsSymbol() {  let set = {    '+': 1,    '-': 1,    '*': 2,    '/': 2,    '#': 0  }  return function (symbol) {     return set[symbol]  }}math('1+2*(3+4*(5+6))');console.log( math('1+2*(3+4*(5+6))') );