要求:使用 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)
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。