要求:应用 js
实现繁难计算器,可计算蕴含 +
、-
、*
、/
及 ()
的字符串表达式
实现:
const highPriorityRegex = /(?<n1>\d+)\s*?(?<operator>\*|\/)\s*?(?<n2>\d+)/const lowPriorityRegex = /(?<n1>\d+)\s*?(?<operator>\+|\-)\s*?(?<n2>\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}