Created with <3 with dartpad.dev.
Created
October 26, 2022 21:27
-
-
Save iykekings/02516a1ecaf6eaf9e22f817d8fefce51 to your computer and use it in GitHub Desktop.
oval-branch-4643
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
num evaluate(String expr) { | |
var divAndMult = | |
RegExp(r"\(?\s*(\d+(?:\.\d*)?)\s*([/*])\s*(\d+(?:\.\d*)?)\s*\)?"); | |
var addAndSub = | |
RegExp(r"\(?\s*(\d+(?:\.\d*)?)\s*([+-])\s*(\d+(?:\.\d*)?)\s*\)?"); | |
var nextInput = expr; | |
while (divAndMult.hasMatch(nextInput) || addAndSub.hasMatch(nextInput)) { | |
var first = nextInput.replaceAllMapped(divAndMult, (match) { | |
if (match[2] == "*") { | |
return (num.parse(match[1]!) * num.parse(match[3]!)).toString(); | |
} | |
return (num.parse(match[1]!) / num.parse(match[3]!)).toString(); | |
}); | |
nextInput = first.replaceAllMapped(addAndSub, (match) { | |
if (match[2] == "+") { | |
return (num.parse(match[1]!) + num.parse(match[3]!)).toString(); | |
} | |
return (num.parse(match[1]!) - num.parse(match[3]!)).toString(); | |
}); | |
} | |
return num.parse(nextInput); | |
} | |
void main() { | |
print(evaluate("(8 * 8) - (20 / 5) + 8")); | |
print(evaluate("( 2 + 12 )")); | |
print(evaluate("100 * ( 2 + 12 ) / 14")); | |
print(evaluate("10.5 + 2 * 6")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment