使用 JS 实现简易计算器

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

const highPriorityRegex = /(?\d+)\s*?(?\*|\/)\s*?(?\d+)/
const lowPriorityRegex = /(?\d+)\s*?(?\+|\-)\s*?(?\d+)/

function calc(str: string) {
  // 先查找左侧括号
  const lI = [...str].findIndex(c => c === '(');

  if (lI > -1) {
    // 找寻对应的右侧括号
    const rI = [...str].findLastIndex(c => c === ')');
    // 将括号内的内容通过递归的形式得到结果后,在替换回去
    str = str.slice(0, lI) + calc(str.slice(lI + 1, rI)) + str.slice(rI + 1)
  }

  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
}

你可能感兴趣的:(javascript)