Skip to content

Instantly share code, notes, and snippets.

@iykekings
Created October 26, 2022 21:27
Show Gist options
  • Save iykekings/02516a1ecaf6eaf9e22f817d8fefce51 to your computer and use it in GitHub Desktop.
Save iykekings/02516a1ecaf6eaf9e22f817d8fefce51 to your computer and use it in GitHub Desktop.
oval-branch-4643
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