要求:使用 js 实现简易计算器,可计算包含 +-*/() 的字符串表达式
实现:

const parenthesisRegex = /(?<=(\((?<expression>.*?)))\)/;
const highPriorityRegex = /(?<n1>\d+)\s*?(?<operator>\*|\/)\s*?(?<n2>\d+)/
const lowPriorityRegex = /(?<n1>\d+)\s*?(?<operator>\+|\-)\s*?(?<n2>\d+)/

function calcCore(str: string) {
  let matches;

  // 先匹配乘除
  while ((matches = str.match(highPriorityRegex))) {
    const { 0: { length }, groups, index } = matches;
    const { n1, n2, operator } = groups!
    const res = operator === '*' ? (+n1 * +n2) : (+n1 / +n2)

    str = str.slice(0, index!) + `${res}` + str.slice(index! + length)
  }

  // 再处理加减
  while ((matches = str.match(lowPriorityRegex))) {
    const { 0: { length }, groups, index } = matches;
    const { n1, n2, operator } = groups!
    const res = operator === '+' ? (+n1 + +n2) : (+n1 - +n2)

    str = str.slice(0, index!) + `${res}` + str.slice(index! + length)
  }

  return +str
}

function calc(str: string) {
  let matches;

  while((matches = str.match(parenthesisRegex))) {
    const { index: rI, groups } = matches
    const { expression } = groups!;
    const lI = rI! - matches[1].length;

    str = str.slice(0, lI) + `${calcCore(expression)}` + str.slice(rI! + 1)
  }

  return calcCore(str)
}

winter
21 声望5 粉丝